轉自:樓教主的分享。 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 命令行下不會負數,以下圖: