YIIRedisConnection.php 2.39 KB
<?php

namespace common\components\redis;

use common\components\redis\transaction\MultiExec as MultiExecTransaction;

/**
 * 兼容 "yii-redis"扩展的类 运行 yii 的 "composer require yiisoft/yii2-redis" 集成
 * Class YIIRedisConnection
 * @package common\components\redis
 */
class YIIRedisConnection extends BaseConnection
{
    /**
     * @var float 使用redis socket 读和写操作的超时时间. 如果没有被设置,那么PHP的默认设置:Socket连接超时间将会被启用.
     */
    public $dataTimeout;

    public function init()
    {
        if (!class_exists('\yii\redis\Connection')) {
            throw new \Exception('the extension yii\redis\Connection does not exist ,you need it to operate redis ,you can run "composer require yiisoft/yii2-redis" to gei it!');
        }

        if (null === $this->connection) {
            $this->connection = \Yii::createObject([
                'class' => 'yii\redis\Connection',
                'hostname' => $this->hostname,
                'password' => $this->password,
                'port' => $this->port,
                'database' => $this->database,
                'connectionTimeout' => $this->connectionTimeout,
                'dataTimeout' => $this->dataTimeout
            ]);
        }
    }

    /**
     * 当前驱动器名称,yii redis 和 php redis 两种,一个是yii2的redis扩展,一个是PHP的C扩展
     * @return string 当前驱动器名称
     */
    public function getDriverName()
    {
        return 'yii redis';
    }
    
    /**
     * 打开一个REDIS连接
     * 如果已经打开过了,直接返回,什么都不做。
     * @throws Exception 连接失败
     */
    public function getIsActive()
    {
        return $this->connection->getIsActive();
    }

    /**
     * 打开一个REDIS连接
     * It does nothing if a DB connection has already been established.
     * @throws Exception if connection fails
     */
    public function open()
    {
        $this->connection->open();
    }

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

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