转自:楼教主的分享。 php
安装后,打开 common/config/main.php 文件,修改以下:redis
'cache' => [ // 'class' => 'yii\caching\FileCache', 'class' => 'yii\redis\Cache', ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ],
如上配置以后,如今已经用 redis 接管了yii的缓存,缓存的使用和之前同样,之前怎么用如今仍是怎么用。
Yii::$app->cache->set('test', 'hehe..');
echo Yii::$app->cache->get('test'), "\n"; Yii::$app->cache->set('test1', 'haha..', 5); echo '1 ', Yii::$app->cache->get('test1'), "\n"; sleep(6); echo '2 ', Yii::$app->cache->get('test1'), "\n";
如上测试结果:
如上和原来同样的用法,没问题。
若是你直接用 redis 接管了 cache,若是正常使用是彻底没问题的,可是当 过时时间 的值超过 int 范围的时候,redis就会报错。
我使用了 yii2-admin,由于他缓存了30天,也就是2592000秒,而且 redis 缓存时间精度默认用毫秒,因此时间就是 2592000000 毫秒。
而 redis 的过时时间只能是int类型,Cache.php 里的 php 强制转为int,而没有作其余处理,因此就会变成 -1702967296 而后就报错了。以下图:
修复上面的Bug,咱们修改成秒便可。缓存
打开 vendor/yiisoft/yii2-redis/Cache.php 第 133 行,修改成以下代码:yii2
protected function setValue($key, $value, $expire)
{
if ($expire == 0) {
return (bool) $this->redis->executeCommand('SET', [$key, $value]);
} else {
// $expire = (int) ($expire * 1000); // 单位默认为毫秒
// return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire]);
$expire = +$expire > 0 ? $expire : 0; // 防止负数
return (bool) $this->redis->executeCommand('SET', [$key, $value, 'EX', $expire]); // 按秒缓存
}
}
可是直接在 redis 命令行下不会负数,以下图: