webman极简redis缓存插件

v1.0.3 版本
2022-10-25 版本更新时间
730 安装
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' => '',

    // 数据库编号
    'database' => 0,

    // key前缀
    'prefix' => 'webman_redis_cache',

    // 默认缓存时间(秒)
    'default_expire' => 3600,

    // 最大缓存时间(秒)
    'max_expire' => 86400 * 100,
];

使用步骤

// 1. 引入缓存类
use Cgophp\WebmanRedisCache\RedisCache;

// 2. 调用
// 缓存时间可以不设置,默认为配置文件中设置的 default_expire
$result = RedisCache::get(缓存key, function () {
    // 当缓存key在redis里没有时,才会调用这里的闭包
    // 闭包只需返回缓存数据即可
    // 例如
    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秒,一直刷新浏览器,你会发现10秒后时间会变
        $result = RedisCache::get('test_key', function () use ($name) {
            return $name . '---' . date('Y-m-d H:i:s');
        }, 10);

        return json($result);
    }

}

添加到助手函数

/app/functions.php

// 获取redis缓存
function get_redis_cache($key, $callback, $expire = 0)
{
    return \Cgophp\WebmanRedisCache\RedisCache::get($key, $callback, $expire);
}

// 调用示例
$result = get_redis_cache('test_key', function () {
    return [
        'name' => '张三',
        'time' => date('Y-m-d H:i:s'),
    ];
});

var_dump($result);

效果图(可选)