我在使用thinkphp3.2.3的時候 發現如果是使用redis緩存 設置了認證的redis能連接成功 卻無法 set 操作 ,檢查發現是沒有認證導致的 $redis->auth這一步沒有,那么官方給出的 Redis.class.php沒有的話,我們可以自己加上,在構造函數第29行 將以前的代碼改為:
以前代碼如下:
$options = array_merge(array ( 'host' => C('REDIS_HOST') ? : '127.0.0.1', 'port' => C('REDIS_PORT') ? : 6379, 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 'persistent' => false, ),$options);
加一行 'auth' => C('REDIS_AUTH_PASSWORD') ? C('REDIS_AUTH_PASSWORD'):null,//auth認證的密碼 ,改為這樣
$options = array_merge(array ( 'host' => C('REDIS_HOST') ? : '127.0.0.1', 'port' => C('REDIS_PORT') ? : 6379, 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 'auth' => C('REDIS_AUTH_PASSWORD') ? C('REDIS_AUTH_PASSWORD'):null,//auth認證的密碼 'persistent' => false, ),$options);
這樣就能在options中讀取到是否啟用認證的密碼了,然后后面加一個判斷
在這段代碼后面
$this->handler = new \Redis; $options['timeout'] === false ? $this->handler->$func($options['host'], $options['port']) : $this->handler->$func($options['host'], $options['port'], $options['timeout']);
加上一個判斷,判斷是否啟用了認證密碼配置 啟用了就去認證一下
if($this->options['auth']!==null) { $this->handler->auth($this->options['auth']); //說明有配置redis的認證配置密碼 需要認證一下 }
總體來看,構造方法被改為了如下:
public function __construct($options=array()) { if ( !extension_loaded('redis') ) { E(L('_NOT_SUPPORT_').':redis'); } $options = array_merge(array ( 'host' => C('REDIS_HOST') ? : '127.0.0.1', 'port' => C('REDIS_PORT') ? : 6379, 'timeout' => C('DATA_CACHE_TIMEOUT') ? : false, 'auth' => C('REDIS_AUTH_PASSWORD') ? C('REDIS_AUTH_PASSWORD'):null,//auth認證的密碼 'persistent' => false, ),$options); $this->options = $options; $this->options['expire'] = isset($options['expire'])? $options['expire'] : C('DATA_CACHE_TIME'); $this->options['prefix'] = isset($options['prefix'])? $options['prefix'] : C('DATA_CACHE_PREFIX'); $this->options['length'] = isset($options['length'])? $options['length'] : 0; $func = $options['persistent'] ? 'pconnect' : 'connect'; $this->handler = new \Redis; $options['timeout'] === false ? $this->handler->$func($options['host'], $options['port']) : $this->handler->$func($options['host'], $options['port'], $options['timeout']); if($this->options['auth']!=null) { $this->handler->auth($this->options['auth']); //說明有配置redis的認證配置密碼 需要認證一下 } }
然后配置文件里面加上 "REDIS_AUTH_PASSWORD"=>"redis認證密碼" 即可