Yii2的Redis包含两种存储方式:
Cache
Session
安装
使用composer安装
推荐安装方式是使用composer。
在composer.json里的require节加上:
"yiisoft/yii2-redis": "~2.0.0"
修改配置文件
return [ //.... 'components' => [ 'redis' => [ 'class' => 'yii\redis\Connection', 'hostname' => 'localhost', 'port' => 6379, 'database' => 0, ], ] ];
使用
下面使用函数就比较简单了
Yii::$app->redis->set('a','12345');有部分函数使用时要注意,比如mget:
$tempkeyarray=explode(',',$tempkey);
$resultarray = Yii::$app->redis->executeCommand('mget',$tempkeyarray);问题处理
yii2-redis在使用时,有时会不稳定,经常报错,错误指向:
Connection.php的 386行:
/**
* @param string $command
* @return mixed
* @throws Exception on error
*/
private function parseResponse($command)
{
if (($line = fgets($this->_socket)) === false) {
throw new Exception("Failed to read from socket.\nRedis command was: " . $command);
}解决方法:
修改php.ini,设置:
default_socket_timeout = -1
可以在index.php入口处加:
<?php
ini_set('default_socket_timeout', -1);