sevenlab/laravel-responsecache

在Laravel应用中缓存响应

2.1.0 2023-03-01 09:42 UTC

This package is auto-updated.

Last update: 2024-09-29 13:04:11 UTC


README

Latest Version on Packagist Software License Total Downloads

缓存响应

此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文件中指定的缓存存储(config/cache.php)和responsecache文件中指定的标签的所有内容(config/responsecache.php)。

也可以通过执行以下Artisan命令实现相同的结果

php artisan responsecache:clear

鸣谢