Home > Article > Backend Development > Yii2-Redis usage notes, yii2-redis notes_PHP tutorial
I briefly learned Redis a few days ago, and now I am ready to use it on the project. We are currently using the Yii2 framework. After searching for Redis on the official website, we found the yii2-redis extension.
It is 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 the same way I used it before, but there is a bug that is not a bug, so it is a small pitfall. I will talk about 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";
Let’s take a look at the test results.
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 hole. What is it?
If you directly use redis to take over the cache, it will be no problem if used normally. However, when the expiration time value exceeds the int range, redis will report an error.
I used yii2-admin, which happened to be a trap for me, because it cached 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 there will be no negative number 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 OK.
Okay, let’s share these today, and I will talk about Connection, ActiveRecord and pitfalls of yii2-redis tomorrow and the day after tomorrow.