PHPRedisConnection.php 2.16 KB
<?php namespace common\components\redis;

/**
 * 兼容 "php redis" 扩展的类(@see http://pecl.php.net/package/redis)
 * Class PHPRedisConnection
 * @package common\components\redis
 */
class PHPRedisConnection extends BaseConnection
{
    private $_isActive = false;

    public function init()
    {
        if (!class_exists('\Redis')) {
            throw new \Exception('the php extension \Redis does not exist ,you need it to operate redis ,you can install from http://pecl.php.net/package/redis');
        }

        $this->connection = new \Redis();
    }

    /**
     * 当前驱动器名称,yii redis 和 php redis 两种,一个是yii2的redis扩展,一个是PHP的C扩展
     * @return string 当前驱动器名称
     */
    public function getDriverName()
    {
        return 'php redis';
    }

    /**
     * 当前REDIS链接是否有效
     * @return boolean 当前REDIS链接是否有效
     */
    public function getIsActive()
    {
        return $this->_isActive;
    }

    /**
     * 打开一个REDIS连接
     * 如果已经打开过了,直接返回,什么都不做。
     * @return void
     * @throws Exception 连接失败
     */
    public function open()
    {
        if ($this->_isActive !== false) {
            return;
        }

        //如果设置了链接超时
        if(null !== $this->connectionTimeout){
            $this->_isActive  = $this->connection->connect($this->hostname, $this->port, $this->connectionTimeout);
        } else {
            $this->_isActive  = $this->connection->connect($this->hostname, $this->port);
        }

        if($this->_isActive){
            if ($this->password !== null) {
                $this->auth($this->password);
            }
            $this->select($this->database);
        }
    }

    /**
     * 关闭当前REDIS连接
     * @return void
     */
    public function close()
    {
        $this->connection->close();
    }

    /**
     * 代理 \Redis 对应的方法
     * @param $name
     * @param $params
     * @return mixed
     */
    protected function call($name, $params)
    {
        $this->open();
        return call_user_func_array([$this->connection, $name], $params);
    }
}