Cache緩存
webman/cache是基于symfony/cache開發(fā)的緩存組件,兼容協(xié)程和非協(xié)程環(huán)境,支持連接池。
注意
當(dāng)前手冊為 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
,如果沒有請手動(dòng)創(chuàng)建。
配置文件內(nèi)容
<?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種驅(qū)動(dòng),file、redis、array、apcu。
file 文件驅(qū)動(dòng)
此為默認(rèn)驅(qū)動(dòng),不依賴其它組件,支持跨進(jìn)程共享緩存數(shù)據(jù),不支持多服務(wù)器共享緩存數(shù)據(jù)。
array 內(nèi)存驅(qū)動(dòng)
內(nèi)存存儲(chǔ),性能最好,但是會(huì)占用內(nèi)存,不支持跨進(jìn)程跨服務(wù)器共享數(shù)據(jù),進(jìn)程重啟后失效,一般用于緩存數(shù)據(jù)量小的項(xiàng)目。
apcu 內(nèi)存驅(qū)動(dòng)
內(nèi)存存儲(chǔ),性能僅次于 array,支持跨進(jìn)程共享緩存數(shù)據(jù),不支持多服務(wù)器共享緩存數(shù)據(jù),進(jìn)程重啟后失效,一般用于緩存數(shù)據(jù)量小的項(xiàng)目。
需要安裝并啟用 APCu 擴(kuò)展;不建議用于頻繁進(jìn)行緩存寫入/刪除的場景,會(huì)導(dǎo)致明顯的性能下降。
redis 驅(qū)動(dòng)
依賴webman/redis組件,支持跨進(jìn)程跨服務(wù)器共享緩存數(shù)據(jù)。
stores.redis.connection
stores.redis.connection
對應(yīng)的是config/redis.php
里對應(yīng)的key。當(dāng)使用redis時(shí),會(huì)復(fù)用webman/redis
的配置包括連接池配置。
建議在config/redis.php
增加一個(gè)獨(dú)立的配置,例如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
設(shè)置為cache
,config/cache.php
最終配置類似如下
<?php
return [
'default' => 'redis', // <====
'stores' => [
'file' => [
'driver' => 'file',
'path' => runtime_path('cache')
],
'redis' => [
'driver' => 'redis',
'connection' => 'cache' // <====
],
'array' => [
'driver' => 'array'
]
]
];
切換存儲(chǔ)
可以通過如下代碼手動(dòng)切store,從而使用不同的存儲(chǔ)驅(qū)動(dòng),例如
Cache::store('redis')->set('key', 'value');
Cache::store('array')->set('key', 'value');
提示
Key 名受 PSR6 限制不允許包含{}()/\@:
中任一字符,但這一判斷截至目前(symfony/cache
7.2.4)可暫時(shí)通過 PHP ini 配置zend.assertions=-1
跳過。
使用其它Cache組件
ThinkCache組件使用參考 其它數(shù)據(jù)庫