Cache
在webman默認使用 symfony/cache作為cache組件。
注意
Cache 組件在2024-09-15進行了升級,此文檔需要workerman/webman-framework
版本 >= 1.5.24
通過composer info
命令查看workerman/webman-framework
版本,通過命令composer require workerman/webman-framework ^1.5.24
升級。
安裝
php 7.x
composer require -W symfony/cache ^5.2 psr/simple-cache
php 8.x
composer require -W symfony/cache psr/simple-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
。如果你的webman沒有這個文件說明框架不是最新的,請手動創(chuàng)建config/cache.php
,并在項目根目錄執(zhí)行 composer require workerman/webman-framework ^1.5.24
升級 workerman/webman-framework
。
配置文件內(nèi)容
<?php
return [
'default' => 'file',
'stores' => [
'file' => [
'driver' => 'file',
'path' => runtime_path('cache')
],
'redis' => [
'driver' => 'redis',
'connection' => 'default'
],
'array' => [
'driver' => 'array'
]
]
];
stores.driver
支持3種驅(qū)動,file、redis、array。
file 文件驅(qū)動
此為默認驅(qū)動,可通過'default' => 'xxx'
字段更改。
redis 驅(qū)動
Redis存儲,如需使用請先安裝Redis組件,命令如下
- php 7.x
composer require -W illuminate/redis ^8.2.0
- php 8.x
composer require -W illuminate/redis
提示
要想使用illuminate/redis
請確保php-cli
安裝了Redis擴展,執(zhí)行php -m
查看php-cli
支持的擴展。
stores.redis.connection
stores.redis.connection 對應的是config/redis.php
里對應的key。建議在config/redis.php
創(chuàng)建一個獨立的key,例如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
設置為cache
,config/cache.php
最終配置類似如下
<?php
return [
'default' => 'redis', // <===
'stores' => [
'file' => [
'driver' => 'file',
'path' => runtime_path('cache')
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache' // <====
],
'array' => [
'driver' => 'array'
]
]
];
array 內(nèi)存驅(qū)動
內(nèi)存存儲,性能最好,但是會占用內(nèi)存,一般用于緩存數(shù)據(jù)量小的項目。
切換存儲
可以通過如下代碼手動切store,從而使用不同的存儲驅(qū)動,例如
Cache::store('redis')->set('key', 'value');
Cache::store('array')->set('key', 'value');
提示
symfony/cache 的key不允許包含字符"{}()/\@:"
使用其它Cache組件
ThinkCache組件使用參考 其它數(shù)據(jù)庫