这个 Laravel 包可以缓存整个响应。默认情况下,它将缓存所有返回基于文本的内容(例如 html 和 json)的成功获取请求一周。这可能会大大加快响应速度。
因此,第一次请求进入包时将保存响应,然后再将其发送给用户。当相同的请求再次出现时,我们不会遍历整个应用程序,而只是使用保存的响应进行响应。
你是视觉学习者吗?然后观看此视频,其中介绍了如何使用 laravel-responsecache 及其幕后工作原理。
我们投入了大量资源来创建一流的开源包。您可以通过购买我们的一款付费产品来支持我们。
我们非常感谢您从家乡寄给我们一张明信片,并注明您正在使用我们的哪种套餐。您可以在我们的联系页面上找到我们的地址。我们在虚拟明信片墙上发布所有收到的明信片。
如果您使用 PHP 7,请安装此软件包的 v6.x。
您可以通过 Composer 安装该软件包:
composer require spatie/laravel-responsecache
该包将自动注册。
您可以使用以下方式发布配置文件:
php artisan vendor:publish --tag= " responsecache-config "
这是已发布的配置文件的内容:
// config / responsecache . php
return [
/ *
* Determine if the response cache middleware should be enabled .
* /
' enabled ' => env ( ' RESPONSE_CACHE_ENABLED ' , true ),
/ *
* The given class will determinate if a request should be cached . The
* default class will cache all successful GET - requests .
*
* You can provide your own class given that it implements the
* CacheProfile interface .
* /
' cache_profile ' => Spatie ResponseCache CacheProfiles CacheAllSuccessfulGetRequests::class,
/ *
* Optionally , you can specify a header that will force a cache bypass .
* This can be useful to monitor the performance of your application .
* /
' cache_bypass_header ' => [
' name ' => env ( ' CACHE_BYPASS_HEADER_NAME ' , null ),
' value ' => env ( ' CACHE_BYPASS_HEADER_VALUE ' , null ),
],
/ *
* When using the default CacheRequestFilter this setting controls the
* default number of seconds responses must be cached .
* /
' cache_lifetime_in_seconds ' => env ( ' RESPONSE_CACHE_LIFETIME ' , 60 * 60 * 24 * 7 ),
/ *
* This setting determines if a http header named with the cache time
* should be added to a cached response . This can be handy when
* debugging .
* /
' add_cache_time_header ' => env ( ' APP_DEBUG ' , true ),
/ *
* This setting determines the name of the http header that contains
* the time at which the response was cached
* /
' cache_time_header_name ' => env ( ' RESPONSE_CACHE_HEADER_NAME ' , ' laravel-responsecache ' ),
/ *
* This setting determines if a http header named with the cache age
* should be added to a cached response . This can be handy when
* debugging .
* ONLY works when "add_cache_time_header" is also active !
* /
' add_cache_age_header ' => env ( ' RESPONSE_CACHE_AGE_HEADER ' , false ),
/ *
* This setting determines the name of the http header that contains
* the age of cache
* /
' cache_age_header_name ' => env ( ' RESPONSE_CACHE_AGE_HEADER_NAME ' , ' laravel-responsecache-age ' ),
/ *
* Here you may define the cache store that should be used to store
* requests . This can be the name of any store that is
* configured in app / config / cache . php
* /
' cache_store ' => env ( ' RESPONSE_CACHE_DRIVER ' , ' file ' ),
/ *
* Here you may define replacers that dynamically replace content from the response .
* Each replacer must implement the Replacer interface .
* /
' replacers ' => [
Spatie ResponseCache Replacers CsrfTokenReplacer::class,
],
/ *
* If the cache driver you configured supports tags , you may specify a tag name
* here . All responses will be tagged . When clearing the responsecache only
* items with that tag will be flushed .
*
* You may use a string or an array here .
* /
' cache_tag ' => '' ,
/ *
* This class is responsible for generating a hash for a request . This hash
* is used to look up an cached response .
* /
' hasher ' => Spatie ResponseCache Hasher DefaultHasher::class,
/ *
* This class is responsible for serializing responses .
* /
' serializer ' => Spatie ResponseCache Serializers DefaultSerializer::class,
];
最后,您应该安装提供的中间件SpatieResponseCacheMiddlewaresCacheResponse::class
和SpatieResponseCacheMiddlewaresDoNotCacheResponse
。
对于 laravel 11.x 及更高版本:
将中间件定义添加到引导应用程序。
// bootstrap / app . php
-> withMiddleware ( function ( Middleware $ middleware ) {
. . .
$ middleware -> web (append: [
...
Spatie ResponseCache Middlewares CacheResponse::class,
]);
. . .
$ middleware -> alias ([
...
' doNotCacheResponse ' => Spatie ResponseCache Middlewares DoNotCacheResponse::class,
]);
})
对于 laravel 10.x 及更早版本:
将中间件定义添加到 http 内核。
// app / Http / Kernel . php
. . .
protected $ middlewareGroups = [
' web ' => [
...
Spatie ResponseCache Middlewares CacheResponse::class,
],
...
protected $ middlewareAliases = [
...
' doNotCacheResponse ' => Spatie ResponseCache Middlewares DoNotCacheResponse::class,
];
默认情况下,该包会将所有成功的GET
请求缓存一周。每个登录用户都有自己单独的缓存。如果您需要这种行为,那么您就完成了:安装ResponseCacheServiceProvider
就足够了。
可以使用以下命令清除整个缓存:
ResponseCache:: clear ();
这将清除配置文件中指定的缓存存储中的所有内容。
可以通过发出以下 artisan 命令来完成同样的任务:
php artisan responsecache:clear
每当保存或删除模型时,您都可以利用模型事件来清除缓存。这是一个例子。
namespace App Traits ;
use Spatie ResponseCache Facades ResponseCache ;
trait ClearsResponseCache
{
public static function bootClearsResponseCache ()
{
self :: created ( function () {
ResponseCache:: clear ();
});
self :: updated ( function () {
ResponseCache:: clear ();
});
self :: deleted ( function () {
ResponseCache:: clear ();
});
}
}
您可以通过以下方式忘记特定的 URI:
// Forget one
ResponseCache:: forget ( ' /some-uri ' );
// Forget several
ResponseCache:: forget ([ ' /some-uri ' , ' /other-uri ' ]);
// Equivalent to the example above
ResponseCache:: forget ( ' /some-uri ' , ' /other-uri ' );
ResponseCache::forget
方法仅在您未在缓存配置文件中使用cacheNameSuffix
时才有效,请使用ResponseCache::selectCachedItems
来处理cacheNameSuffix
。
您可以使用ResponseCache::selectCachedItems()
指定应忘记哪些缓存项。
// forgetting all PUT responses of / some - uri
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ( ' /some-uri ' )-> forget ();
// forgetting all PUT responses of multiple endpoints
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ([ ' /some-uri ' , ' /other-uri ' ])-> forget ();
// this is equivalent to the example above
ResponseCache:: selectCachedItems ()-> withPutMethod ()-> forUrls ( ' /some-uri ' , ' /other-uri ' )-> forget ();
// forget / some - uri cached with "100" suffix ( by default suffix is user - > id or "" )
ResponseCache:: selectCachedItems ()-> usingSuffix ( ' 100 ' )-> forUrls ( ' /some-uri ' )-> forget ();
// all options combined
ResponseCache:: selectCachedItems ()
-> withPutMethod ()
-> withHeaders ([ ' foo ' => ' bar ' ])
-> withCookies ([ ' cookie1 ' => ' value ' ])
-> withParameters ([ ' param1 ' => ' value ' ])
-> withRemoteAddress ( ' 127.0.0.1 ' )
-> usingSuffix ( ' 100 ' )
-> usingTags ( ' tag1 ' , ' tag2 ' )
-> forUrls ( ' /some-uri ' , ' /other-uri ' )
-> forget ();
cacheNameSuffix
取决于您的缓存配置文件,默认情况下是用户 ID,如果未经过身份验证,则为空字符串。
使用doNotCacheResponse
中间件可以忽略请求。该中间件可以分配给路由和控制器。
使用中间件我们的路由可以免于被缓存。
// app / Http / routes . php
Route:: get ( ' /auth/logout ' , [ ' middleware ' => ' doNotCacheResponse ' , ' uses ' => ' AuthController@getLogout ' ]);
或者,您可以将中间件添加到控制器:
class UserController extends Controller
{
public function __construct ()
{
$ this -> middleware ( ' doNotCacheResponse ' , [ ' only ' => [ ' fooAction ' , ' barAction ' ]]);
}
}
可以有目的地、安全地绕过缓存并确保您始终收到新的响应。如果您想要分析某个端点或需要调试响应,这可能很有用。在任何情况下,您所需要做的就是填充CACHE_BYPASS_HEADER_NAME
和CACHE_BYPASS_HEADER_VALUE
环境变量,然后在执行请求时使用该自定义标头。
为了确定应该缓存哪些请求以及缓存多长时间,需要使用缓存配置文件类。处理这些问题的默认类是SpatieResponseCacheCacheProfilesCacheAllSuccessfulGetRequests
。
您可以通过实现SpatieResponseCacheCacheProfilesCacheProfile
接口来创建自己的缓存配置文件类。我们看一下界面:
interface CacheProfile
{
/ *
* Determine if the response cache middleware should be enabled .
* /
public function enabled ( Request $ request ): bool ;
/ *
* Determine if the given request should be cached .
* /
public function shouldCacheRequest ( Request $ request ): bool ;
/ *
* Determine if the given response should be cached .
* /
public function shouldCacheResponse ( Response $ response ): bool ;
/ *
* Return the time when the cache must be invalidated .
* /
public function cacheRequestUntil ( Request $ request ): DateTime ;
/ * *
* Return a string to differentiate this request from others .
*
* For example : if you want a different cache per user you could return the id of
* the logged in user .
*
* @ param Illuminate Http Request $ request
*
* @ return mixed
* /
public function useCacheNameSuffix ( Request $ request );
}
您也可以将其注册为路由中间件,而不是全局注册cacheResponse
中间件。
protected $ middlewareAliases = [
...
' cacheResponse ' => Spatie ResponseCache Middlewares CacheResponse::class,
];
使用路由中间件时,您可以指定这些路由应缓存的秒数:
// cache this route for 5 minutes
Route:: get ( ' /my-special-snowflake ' , ' SnowflakeController@index ' )-> middleware ( ' cacheResponse:300 ' );
// cache all these routes for 10 minutes
Route:: group ( function () {
Route:: get ( ' /another-special-snowflake ' , ' AnotherSnowflakeController@index ' );
Route:: get ( ' /yet-another-special-snowflake ' , ' YetAnotherSnowflakeController@index ' );
})-> middleware ( ' cacheResponse:600 ' );
如果您配置的缓存驱动程序支持标签,您可以在应用中间件时指定标签列表。
// add a "foo" tag to this route with a 300 second lifetime
Route:: get ( ' /test1 ' , ' SnowflakeController@index ' )-> middleware ( ' cacheResponse:300,foo ' );
// add a "bar" tag to this route
Route:: get ( ' /test2 ' , ' SnowflakeController@index ' )-> middleware ( ' cacheResponse:bar ' );
// add both "foo" and "bar" tags to these routes
Route:: group ( function () {
Route:: get ( ' /test3 ' , ' AnotherSnowflakeController@index ' );
Route:: get ( ' /test4 ' , ' YetAnotherSnowflakeController@index ' );
})-> middleware ( ' cacheResponse:foo,bar ' );
您可以清除分配了标签或标签列表的响应。例如,此语句将删除上面的'/test3'
和'/test4'
路由:
ResponseCache:: clear ([ ' foo ' , ' bar ' ]);
相反,此语句将仅删除'/test2'
路由:
ResponseCache:: clear ([ ' bar ' ]);
请注意,这使用了 Laravel 内置的缓存标签功能,这意味着也可以通过通常的方式清除路由:
Cache:: tags ( ' special ' )-> flush ();
您可以使用多个事件来监视和调试应用程序中的响应缓存。
SpatieResponseCacheEventsResponseCacheHit
当请求通过ResponseCache
中间件并且找到并返回缓存的响应时,会触发此事件。
SpatieResponseCacheEventsCacheMissed
当请求通过ResponseCache
中间件但未找到或返回缓存的响应时,会触发此事件。
SpatieResponseCacheEventsClearingResponseCache
SpatieResponseCacheEventsClearedResponseCache
这些事件分别在responsecache:clear
启动和完成时触发。
要用动态内容替换缓存内容,您可以创建替换器。默认情况下,我们在配置文件中添加CsrfTokenReplacer
。
您可以通过实现SpatieResponseCacheReplacersReplacer
接口来创建自己的替换器。我们看一下界面:
interface Replacer
{
/ *
* Prepare the initial response before it gets cached .
*
* For example : replace a generated csrf_token by '<csrf-token-here>' that you can
* replace with its dynamic counterpart when the cached response is returned .
* /
public function prepareResponseToCache ( Response $ response ): void ;
/ *
* Replace any data you want in the cached response before it gets
* sent to the browser .
*
* For example : replace '<csrf-token-here>' by a call to csrf_token ()
* /
public function replaceInCachedResponse ( Response $ response ): void ;
}
之后,您可以在responsecache.php
配置文件中定义替换器:
/*
* Here you may define replacers that dynamically replace content from the response.
* Each replacer must implement the Replacer interface.
*/
'replacers' => [
SpatieResponseCacheReplacersCsrfTokenReplacer::class,
],
序列化器负责序列化响应,以便将其存储在缓存中。它还负责从缓存重建响应。
默认序列化器SpatieResponseCacheSerializerDefaultSerializer
在大多数情况下都可以工作。
如果您有一些特殊的序列化需求,您可以在配置文件的serializer
键中指定自定义序列化程序。可以使用任何实现SpatieResponseCacheSerializersSerializer
的类。该界面如下所示:
namespace Spatie ResponseCache Serializers ;
use Symfony Component HttpFoundation Response ;
interface Serializer
{
public function serialize ( Response $ response ): string ;
public function unserialize ( string $ serializedResponse ): Response ;
}
您可以使用以下命令运行测试:
composer test
请参阅变更日志以了解最近更改的更多信息。
详细信息请参阅贡献。
如果您发现有关安全的错误,请发送邮件至 [email protected],而不是使用问题跟踪器。
特别感谢 Caneco 的徽标
麻省理工学院许可证 (MIT)。请参阅许可证文件以获取更多信息。