thinkphp5链接redis,ping报错
代码如下:
protected $config = [
'host' => '127.0.0.1',
'port' => 6379,
'password' => '',
'select' => 1,
'timeout' => 0,
'expire' => 0,
'persistent' => false,
'prefix' => '',
] ;
public function __construct()
{
$this->redis = new Redis($this->config);
$this->hash_prefix = 'news_view_counts_';
$this->field_prefix = 'news_';
$this->date = date('Y-m-d');
}
public function index(){
echo "Server is running: " . $this->redis->ping();
dump($this->redis);
}
解决办法:
thinkphp5 已封装好redis链接类,TP5自带的redis封装了一些简单的redis操作命令,适合key-value使用。要想使用原生语句操作redis,可添加一个方法,将redis实例暴露出去。
redis类位置:
\application\common\library\token\driver\Redis.php
添加如下代码:
/*
* 返回原生的redis对象
* @return object
*/
public function getHandler(){
//$this 为thinkphp封装的redis对象
//$this->handler 才能获取到原生的redis对象
return $this->handler;
}
之前的代码更改为:
public function index(){
$obj = $this->redis->getHandler();
echo "Server is running: " . $obj->ping();
dump($this->redis);
}
搞定!
发表评论 取消回复