webman極簡redis緩存插件

v1.0.3
版本
2022-10-25
版本更新時間
1094
安裝
3
star
簡介
webman極簡redis緩存插件
簡化緩存設置和獲取,只需get,無需set(自動判斷當前緩存key是否存在)
自帶斷線重連
安裝
composer require cgophp/webman-redis-cache
使用
配置文件
/config/plugin/cgophp/webman-redis-cache/app.php
return [
// 是否開啟插件
'enable' => true,
// 主機
'host' => '127.0.0.1',
// 端口
'port' => 6379,
// 連接超時時間
'timeout' => 30,
// 密碼
'password' => '',
// 數(shù)據(jù)庫編號
'database' => 0,
// key前綴
'prefix' => 'webman_redis_cache',
// 默認緩存時間(秒)
'default_expire' => 3600,
// 最大緩存時間(秒)
'max_expire' => 86400 * 100,
];
使用步驟
// 1. 引入緩存類
use Cgophp\WebmanRedisCache\RedisCache;
// 2. 調(diào)用
// 緩存時間可以不設置,默認為配置文件中設置的 default_expire
$result = RedisCache::get(緩存key, function () {
// 當緩存key在redis里沒有時,才會調(diào)用這里的閉包
// 閉包只需返回緩存數(shù)據(jù)即可
// 例如
return Db::table('user')->where('id', 100)->find();
}, 緩存時間[可選]);
var_dump($result);
// 刪除緩存key
RedisCache::remove('test_key');
在控制器中使用例子如下:
<?php
namespace app\controller;
use support\Request;
// 引入緩存類
use Cgophp\WebmanRedisCache\RedisCache;
class Index
{
public function cache(Request $request)
{
$name = $request->get('name', 'webman');
// 緩存10秒,一直刷新瀏覽器,你會發(fā)現(xiàn)10秒后時間會變
$result = RedisCache::get('test_key', function () use ($name) {
return $name . '---' . date('Y-m-d H:i:s');
}, 10);
return json($result);
}
}
添加到助手函數(shù)
/app/functions.php
// 獲取redis緩存
function get_redis_cache($key, $callback, $expire = 0)
{
return \Cgophp\WebmanRedisCache\RedisCache::get($key, $callback, $expire);
}
// 調(diào)用示例
$result = get_redis_cache('test_key', function () {
return [
'name' => '張三',
'time' => date('Y-m-d H:i:s'),
];
});
var_dump($result);