php操作redis类支持redis断线重连windows和linux均测试通过
<?php namespace Model; //redis操作类 class Redis{ //配置信息 private $host; private $port; private $password; private $connect_times; //断线重连次数,默认0不限制 //连接对象 protected $con = null; function __construct($config){ $this->host = $config['host']; $this->port = $config['port']; $this->password = isset($config['password']) ? $config['password'] : ''; $this->connect_times = isset($config['connect_times']) ? $config['connect_times'] : 0; } private function connect(){ $con = new \Redis(); try{ $con->connect($this->host, $this->port); }catch(\RedisException $ex){ } if(!$con){ return; } if($this->password != ''){ $auth = $con->auth($this->password); if(!$auth){ return; } } $this->con = $con; } //获取连接,支持断线重连 private function GetConnection(){ if(is_null($this->con)){ $this->connect(); } $connect_times = 0; while(true){ try{ //主动抛出提示,但屏蔽输出 @trigger_error('user.notice', E_USER_NOTICE); //执行ping() 但屏蔽输出 @$this->con->ping(); //获取最后提示 $error = error_get_last(); if($error['message'] != 'user.notice'){ //最后的提示 不是 我主动抛出的,说明ping()失败了 throw new \Exception('Redis server went away'); }else{ break; } }catch(\Exception $ex){ //echo $ex->getMessage() . PHP_EOL; //echo 'connecting...' . PHP_EOL; if($this->connect_times > 0 && $connect_times >= $this->connect_times){ break; } $this->con->close(); $this->connect(); $connect_times++; } //休眠1毫秒 usleep(1000); } } //选择数据库 public function Select($db=0){ $this->GetConnection(); $this->con->select($db); } public function Keys($key){ $this->GetConnection(); $data = $this->con->keys($key); return $data === false ? null : $data; } public function Get($key){ $this->GetConnection(); $data = $this->con->get($key); return $data === false ? null : $data; } public function GetJson($key){ $data = $this->Get($key); return is_null($data) ? null : json_decode($data,true); } public function GetRandKey(){ $this->GetConnection(); return $this->con->randomkey(); } public function GetRand(){ $key = $this->GetRandKey(); if(!$key){ return null; } return $this->GetJson($key); } //随机获取,排除某个key public function GetRandDis($disallow_key){ $key = $this->GetRandKey(); if(!$key){ return null; } //排除某个key if($key == $disallow_key){ return null; } return $this->GetJson($key); } //设置key 永久有效 public function Set($key,$data){ $this->GetConnection(); $this->con->set($key,is_string($data) ? $data : json_encode($data)); } //存入或更新某个key的值 并设置有效期 public function SetEX($key,$data,$expire_seconds){ $this->GetConnection(); $this->con->setex($key,$expire_seconds,is_string($data) ? $data : json_encode($data)); } //删除某个key public function Delete($key){ $this->GetConnection(); $this->con->del($key); } }
调用方法
<?php require_once __DIR__ . '/redis.php'; error_reporting(E_ALL); $hp = new \Model\Redis([ 'host' => '127.0.0.1', 'port' => 6379 ]); $data = $hp->Get('name'); var_dump($data); sleep(5); $data = $hp->Get('name'); var_dump($data); echo 'success' . PHP_EOL;