Cache緩存

webman/cache 是基於 symfony/cache 開發的緩存組件,兼容協程和非協程環境,支持連接池。

注意
當前手冊為 webman v2 版本,如果您使用的是 webman v1 版本,請查看 v1版本手冊

安裝

composer require -W webman/cache

示例

<?php
namespace app\controller;

use support\Request;
use support\Cache;

class UserController
{
    public function db(Request $request)
    {
        $key = 'test_key';
        Cache::set($key, rand());
        return response(Cache::get($key));
    }
}

配置文件位置

配置文件在 config/cache.php,如果沒有請手動創建。

配置文件內容

<?php
return [
    'default' => 'file',
    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => runtime_path('cache')
        ],
        'redis' => [
            'driver' => 'redis',
            'connection' => 'default'
        ],
        'array' => [
            'driver' => 'array'
        ],
        'apcu' => [
            'driver' => 'apcu'
        ]
    ]
];

stores.driver 支持 4 種驅動,fileredisarrayapcu

file 文件驅動

此為默認驅動,不依賴其它組件,支持跨進程共享緩存數據,不支持多服務器共享緩存數據。

array 記憶體驅動

記憶體存儲,性能最好,但是會佔用記憶體,不支持跨進程跨服務器共享數據,進程重啟後失效,一般用於緩存數據量小的項目。

apcu 記憶體驅動

記憶體存儲,性能僅次於 array,支持跨進程共享緩存數據,不支持多服務器共享緩存數據,進程重啟後失效,一般用於緩存數據量小的項目。

需要安裝並啟用 APCu 擴展;不建議用於頻繁進行緩存寫入/刪除的場景,會導致明顯的性能下降。

redis 驅動

依賴 webman/redis 組件,支持跨進程跨服務器共享緩存數據。

stores.redis.connection

stores.redis.connection 對應的是 config/redis.php 裡對應的 key。當使用 redis 時,會重用 webman/redis 的配置包括連接池配置。

建議在 config/redis.php 增加一個獨立的配置,例如 cache 類似如下

<?php
return [
    'default' => [
        'password' => 'abc123',
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 0,
    ],
    'cache' => [ // <==== 新增
        'password' => 'abc123',
        'host' => '127.0.0.1',
        'port' => 6379,
        'database' => 1,
        'prefix' => 'webman_cache-',
    ]
];

然後將 stores.redis.connection 設置為 cacheconfig/cache.php 最終配置類似如下

<?php
return [
    'default' => 'redis', // <====
    'stores' => [
        'file' => [
            'driver' => 'file',
            'path' => runtime_path('cache')
        ],
        'redis' => [
            'driver' => 'redis',
            'connection' => 'cache' // <====
        ],
        'array' => [
            'driver' => 'array'
        ]
    ]
];

切換存儲

可以通過如下代碼手動切 store,從而使用不同的存儲驅動,例如

Cache::store('redis')->set('key', 'value');
Cache::store('array')->set('key', 'value');

提示
Key 名受 PSR6 限制不允許包含 {}()\/@:中任一字符,但這一判斷截至目前(symfony/cache7.2.4)可暫時通過 PHP ini 配置zend.assertions=-1` 跳過。

使用其它Cache組件

ThinkCache 組件使用參考 其它數據庫