前些天簡(jiǎn)單學(xué)習(xí)了下 Redis,現(xiàn)在準(zhǔn)備在項(xiàng)目上使用它了。我們目前用的是 Yii2 框架,在官網(wǎng)搜索了下 Redis,就發(fā)現(xiàn)了yii2-redis這擴(kuò)展。
安裝后使用超簡(jiǎn)單,打開 common/config/main.php 文件,修改如下。
'cache' => [ // 'class' => 'yii/caching/FileCache', 'class' => 'yii/redis/Cache',],'redis' => [ 'class' => 'yii/redis/Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0,],
OK,現(xiàn)在已經(jīng)用 redis 接管了yii的緩存,緩存的使用和以前一樣,以前怎么用現(xiàn)在還是怎么用,但是有個(gè)不算bug的bug,所以算小坑,等會(huì)會(huì)說(shuō)。
來(lái)測(cè)試下 cache 先,
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";來(lái)看下測(cè)試結(jié)果。

和原來(lái)一樣的用法,沒(méi)問(wèn)題。。
但是剛才我說(shuō)過(guò)了有個(gè)不算bug的bug,所以算小坑,到底是什么東西呢?如果你直接用 redis 接管了 cache,如果正常使用是完全沒(méi)問(wèn)題的,但是當(dāng) 過(guò)期時(shí)間 的值超過(guò) int 范圍的時(shí)候,redis就會(huì)報(bào)錯(cuò)。我使用了 yii2-admin,湊巧讓我踩到坑了,因?yàn)樗彺媪?0天,也就是2592000秒,并且 redis 緩存時(shí)間精度默認(rèn)用毫秒,所以時(shí)間就是 2592000000 毫秒。而 redis 的過(guò)期時(shí)間只能是int類型,Cache.php里的php 強(qiáng)制轉(zhuǎn)為int,而沒(méi)有做其他處理,所以就會(huì)變成 -1702967296 然后就報(bào)錯(cuò)了。

但是直接在 redis 命令行下不會(huì)負(fù)數(shù),如圖。

不過(guò)沒(méi)關(guān)系,修復(fù)起來(lái)也很簡(jiǎn)單,我們修改為秒即可。打開 vendor/yiisoft/yii2-redis/Cache.php 第 133 行,修改為如下代碼。
PRotected function setValue($key, $value, $expire){ if ($expire == 0) { return (bool) $this->redis->executeCommand('SET', [$key, $value]); } else { // $expire = (int) ($expire * 1000); // 單位默認(rèn)為毫秒 // return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire]); $expire = +$expire > 0 ? $expire : 0; // 防止負(fù)數(shù) return (bool) $this->redis->executeCommand('SET', [$key, $value, 'EX', $expire]); // 按秒緩存 }}
這樣就OK了。
好了,今天分享這些,明后天會(huì)說(shuō)下 yii2-redis 的 Connection 和 ActiveRecord 以及小坑。
新聞熱點(diǎn)
疑難解答
圖片精選
網(wǎng)友關(guān)注