7lab / laravel-responsecache
2.1.0
2023-03-01 09:42 UTC
Requires
- php: ^7.0|^8.0
- laravel/framework: 5.5.*|5.6.*|5.7.*|5.8.*|^6.0|^7.0|^8.0|^9.0|^10.0
Requires (Dev)
- phpunit/phpunit: ^6.5.4|^7.0
README
缓存响应
此Laravel包可以缓存整个响应。默认情况下,它将缓存所有成功的GET请求一周。这可能会显著加快响应速度。
因此,第一次收到请求时,包将保存响应然后再发送给用户。当相同的请求再次到来时,我们不会通过整个应用程序,而是直接用保存的响应进行响应。
该包基于spatie/laravel-responsecache,但使用定义的路由名称,因此可以轻松清除缓存的响应,而无需清除整个缓存。
安装
您可以通过Composer安装此包
composer require sevenlab/laravel-responsecache
包将自动注册自己。
您可以使用以下命令发布配置文件
php artisan vendor:publish --provider="SevenLab\ResponseCache\ResponseCacheServiceProvider"
这是已发布的配置文件(config/responsecache.php
)的内容
return [ /* * Determine if the response cache middleware should be enabled. */ 'enabled' => env('RESPONSECACHE_ENABLED', true), /* * Specify the tag name that will be used for the cache. */ 'tag' => env('RESPONSECACHE_TAG', 'responsecache'), ];
最后,您应该在HTTP内核(app/Http/Kernel.php
)中安装提供的中间件。
... protected $routeMiddleware = [ ... 'cacheResponse' => \SevenLab\ResponseCache\Middleware\CacheResponse::class, 'doNotCacheResponse' => \SevenLab\ResponseCache\Middleware\DoNotCacheResponse::class, ]; ...
用法
默认情况下,它将缓存所有成功的GET请求一周。登录用户将各自拥有自己的缓存。
缓存特定路由
当使用路由中间件时,您可以指定这些路由应缓存多少分钟
// cache this route for 5 minutes Route::get('/my-special-snowflake', 'SnowflakeController@index')->middleware('cacheResponse:5'); // 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:10');
防止路由被缓存
可以使用doNotCacheResponse
-中间件忽略请求。此中间件可以分配给路由和控制器。
在路由上使用中间件
Route::get('/auth/logout', 'AuthController@getLogout')->name('auth.logout')->middleware('doNotCacheResponse');
或者,您可以将中间件添加到控制器中
class AuthController extends Controller { public function __construct() { $this->middleware('doNotCacheResponse', ['only' => ['getLogout']]); } }
清除特定路由
可以使用以下方式清除特定路由
ResponseCache::forget(['auth.logout']);
同样,也可以通过执行此Artisan命令来实现
php artisan responsecache:forget auth.logout
清除所有路由
可以使用以下方式清除整个缓存
ResponseCache::clear();
这将清除在配置文件(config/cache.php
)中指定的缓存存储中指定的所有内容,标签在responsecache文件(config/responsecache.php
)中指定。
同样,也可以通过执行此Artisan命令来实现
php artisan responsecache:clear