I briefly learned Redis a few days ago, and now I’m ready to use it on projects. We are currently using the Yii2 framework. After searching for Redis on the official website, we found the yii2-redis extension.
It’s super easy to use after installation. Open the common/config/main.php file and modify it as follows.
'cache' => [ // 'class' => 'yii\caching\FileCache', 'class' => 'yii\redis\Cache', ], 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ],
OK, now we have used redis to take over the cache of yii. The use of the cache is the same as before. I still use it how I used it before, but there is a bug that is not a bug, so it is a small pitfall. I will see it later. explain.
Let’s test the cache. First,
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";
take a look at the test results.
The same usage as before, no problem. .
But as I said just now, there is a bug that is not a bug, so it is a small bug. What is it?
If you directly use redis to take over the cache, it will be no problem if used normally, but when the value of expiration time exceeds the int range, redis will report an error.
I used yii2-admin, and it happened that I stepped into a trap, because it cached it for 30 days, which is 2592000 seconds, and the redis cache time precision uses milliseconds by default, so the time is 2592000000 milliseconds.
The expiration time of redis can only be of int type. PHP in Cache.php is forced to convert it to int without any other processing, so it will become -1702967296 and then an error will be reported.
But it will not be negative directly under the redis command line, as shown in the figure.
But it doesn’t matter, it’s very simple to fix, we can just change it to seconds.
Open vendor/yiisoft/yii2-redis/Cache.php line 133 and modify it to the following code.
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]); // 按秒缓存 } }
That’s it.
Okay, let’s share these today, and I will talk about Connection, ActiveRecord and pitfalls of yii2-redis tomorrow and the day after tomorrow.
The above introduces the notes on using Yii2-Redis - Cache, including the relevant aspects. I hope it will be helpful to friends who are interested in PHP tutorials.