redis 实例化以及ping 的操作

来源:互联网 发布:经传全套公式源码 编辑:程序博客网 时间:2024/05/18 03:13

一旦开启一个不关闭的脚本  就需要一个ping函数去不断的校验的链接


下面的redis类经过简单的封装  ; ping 函数由于历史原因并没有封装到 Redis类里面 

class Redis {    protected $handler;    protected $options = [        'persistent' => false,        'host'       => '127.0.0.1',        'port'       => 6379,        'password'   => '',        'select'     => 0,        'timeout'    => 0,    ];    /**     * 架构函数     * @param array $options 配置redis初始化参数     */    public function __construct($options = [])    {        if (!extension_loaded('redis')) {            throw new \BadFunctionCallException('not support: redis');        }        if (!empty($options)) {            $this->options = array_merge($this->options, $options);        }        $this->handler = new \Redis;        $func          = $this->options['persistent'] ? 'pconnect' : 'connect';        $this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);        if ('' != $this->options['password']) {            $this->handler->auth($this->options['password']);        }        if (0 != $this->options['select']) {            $this->handler->select($this->options['select']);        }    }    public function __call($method, $args)    {        return call_user_func_array([$this->handler,$method], $args);    }    //禁止clone    private function __clone() {}    public function __destruct() {        $this->handler->close();    }}


//获取redis实例,单例function getRedis(){    static $redis;    try {        // init redis        if (!$redis) {            $redis = redisInit();        }        // ping redis        $redis = redisPing($redis);        if (!is_object($redis)) {            throw new \RedisException('reconnect redis failed');        }    } catch (\RedisException $e) {        error_log($e->getMessage(), 3, ERROR_LOG);    }    return $redis;}/** * @param $redis * @return Redis|null */function redisPing($redis){    try {        if (!is_object($redis) || !method_exists($redis, 'ping')) {            throw new \RedisException('This connection is down');        }        $response = $redis->ping();        if ($response != '+PONG') {            throw new \RedisException('This connection is down');        }    } catch (\RedisException $e) {        $redis = redisInit();    }    return $redis;}function redisInit(){    // config    $redisConf = array(        'type' => 'redis',        'host' => 'crs-redis.test.cn',        'port' => '6379',    );    // persistent redis    $redisConf['persistent'] = true;        // begin    $redis = null;    $i = 0;    while ($i < 3 && !$redis) {        try {            $redis = new Redis($redisConf);        } catch (\RedisException $e) {            $i++;        }    }    return $redis;}

原创粉丝点击