<?php
namespace Lib;
/**
* Class
*/
class Redis
{
private static $_ins;
private $_redis;
private function __construct()
{
$this->_re_connect();
}
/**
* @return \Redis
*/
static function instance()
{
return self::$_ins ?: (self::$_ins = new self());
}
private function _getRedis()
{
if ($this->_redis === null) {
$this->_redis = new \Redis();
}
return $this->_redis;
}
/**
* @return mixed
*/
private function _re_connect()
{
if (defined('REDIS_PORT') && is_numeric(REDIS_PORT)) {
$this->_getRedis()->pconnect(REDIS_HOST, REDIS_PORT);
} else {
$this->_getRedis()->pconnect(REDIS_HOST);
}
if (defined('REDIS_PASS') && is_string(REDIS_PASS)) {
$this->_getRedis()->auth(REDIS_PASS);
}
}
/**
* @param $name
* @param $arguments
* @return mixed
* @throws \RedisException
*/
public function __call($name, $arguments)
{
if (method_exists($this->_redis, $name)) {
try {
return call_user_func_array([$this->_redis, $name], $arguments);
} catch (\RedisException $e) {
$this->_destruct();
$this->_re_connect();
return call_user_func_array([$this->_redis, $name], $arguments);
}
}
trigger_error('Call to undefined method \\Redis::' . $name . '()', E_USER_ERROR);
}
public function __get($name)
{
if (property_exists($this->_redis, $name)) {
return $this->_redis->{$name};
}
trigger_error('Undefined property: \\Redis::' . $name, E_USER_NOTICE);
}
public function __set($name, $val)
{
if ($name && $val) {
$this->_redis->{$name} = $val;
return;
}
/* if (property_exists($this->_redis, $name)) {
$this->_redis->{$name} = $val;
return;
}
trigger_error('Undefined property: \Redis::' . $name, E_USER_NOTICE);*/
}
private function _destruct()
{
if ($this->_redis) {
$this->_redis->close();
unset($this->_redis);
}
$this->_redis = null;
}
public function __destruct()
{
$this->_destruct();
}
}
使用前需设置//redis配置
define('REDIS_HOST', '127.0.0.1');
//端口默认可注释配置
//define('REDIS_PORT', '6379');
//define('REDIS_PASS', '');