PHP REDIS 使用长连接多数据库存储到最后一个数据库中的问题解决

在使用redis持久连接时,不同的库存储操作不同的数据,但是存储数据时默认存储到最后一个库了,解决方法在最后

风.fox

redis connect 短连接 单例模式没有此问题

class Connect2
{
    /**
     * 类单例数组
     *
     * @var array
     */
    private static $instance = [];
    /**
     * redis连接句柄
     *
     * @var \Redis
     */
    private $redis;
    /**
     * hash的key
     *
     * @var int
     */
    private $db_index;

    /**
     * 私有化构造函数,防止类外实例化
     *
     * @param int $db_index
     */
    private function __construct($options = [], $db_index = 0)
    {
        $config         = config('cache');
        $db_index       = (int)$db_index;
        $this->db_index = $db_index;
        $this->redis    = new \Redis();
        $this->redis->connect($config['host'], $config['port']);
        $this->redis->select($db_index);
    }

    private function __clone()
    {
    }

    /**
     * 获取类单例
     *
     * @param int $db_index
     * @return self
     */
    public static function getRedisInstance($options = [], $db_index = 0)
    {
        $db_index = (int)$db_index;
        if (!isset(self::$instance[$db_index])) {
            self::$instance[$db_index] = new self($options, $db_index);
        }
        return self::$instance[$db_index];
    }

    /**
     * 获取redis的连接实例
     *
     * @return \Redis
     */
    public function getConnect()
    {
        return $this->redis;
    }

    /**
     * 关闭单例时做清理工作
     */
    public function __destruct()
    {
        self::$instance[$this->db_index]->redis->close();
        self::$instance[$this->db_index] = null;
    }
}



$config = config('cache');
$r3     = Connect2::getRedisInstance($config, 3);
$r4     = Connect2::getRedisInstance($config, 4);
$r3->getConnect()->set('33333333333', '22222222', 600);
$r4->getConnect()->set('44444444444', '22222222', 600);

执行上面代码就会在redis缓存中的,db(3),db(4)看到相应的键值。

redis pconnect 持久连接(长连接)会自动存储到最后一个db库中

错误的 类如下

/** redis 参数介绍  http://www.cnblogs.com/weafer/archive/2011/09/21/2184059.html
 * @category    Extend
 * @package     Extend
 * @subpackage  Driver.Cache
 * @author      fox
 */
class RedisAliMulti
{
    protected $options = ['host'       => '127.0.0.1',
                          'port'       => 6379,
                          'password'   => '',
                          'select'     => 0,
                          'timeout'    => 0,
                          'expire'     => 0,
                          'persistent' => false,
                          'prefix'     => '',
    ];
    //数据库编号
    private $db_index;
    /**
     * 类单例数组
     *
     * @var array
     */
    private static $instance = [];
    /**
     * redis连接句柄
     *
     * @var \Redis
     */
    private $handler;

    /**
     * 构造函数
     * @param array $options 缓存参数
     * @param null  $select
     * @access public
     */
    public function __construct($options = [], $select = null)
    {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $func          = $this->options['persistent'] ? 'pconnect' : 'connect';
        $this->handler = new \Redis;
        $this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout']);
        if ('' != $this->options['password']) {
            $this->handler->auth($this->options['password']);
        }
        $this->db_index = (int)$select;
        $this->handler->select($this->db_index);
    }

    /**
     * 析构释放连接
     * @access public
     */
    public function __destruct()
    {
        self::$instance[$this->db_index]->getConnect()->close();
        self::$instance[$this->db_index] = null;
        if (isset($this->handler)) {
            $this->handler->close();
            $this->handler = null;
        }
    }

    /**
     * @return \Redis
     */
    public function getConnect()
    {
        return $this->handler;
    }

    /**
     * 获取类单例
     * @param array $options
     * @param int   $db_index
     * @return self
     */
    public static function getRedisInstance($options = [], $db_index = 0)
    {
        $db_index = (int)$db_index;
        if (!isset(self::$instance[$db_index])) {
            self::$instance[$db_index] = new self($options, $db_index);
        }
        return self::$instance[$db_index];
    }
}

///
//
$r31 = RedisAliMulti::getRedisInstance($config, 3);
$r41 = RedisAliMulti::getRedisInstance($config, 4);
$r31->getConnect()->set('33333333333===', '22222222', 600);
$r41->getConnect()->set('44444444444===', '22222222', 600);

以上执行后,只会在db(4)看到这2个键值,并不是我们预期的db(3)db(4)相应的键值。
解决方法如下:

/** redis 参数介绍  http://www.cnblogs.com/weafer/archive/2011/09/21/2184059.html
 * @category    Extend
 * @package     Extend
 * @subpackage  Driver.Cache
 * @author      fox
 */
class RedisAliMulti
{
    protected $options = ['host'       => '127.0.0.1',
                          'port'       => 6379,
                          'password'   => '',
                          'select'     => 0,
                          'timeout'    => 0,
                          'expire'     => 0,
                          'persistent' => false,
                          'prefix'     => '',
    ];
    //数据库编号
    private $db_index;
    /**
     * 类单例数组
     *
     * @var array
     */
    private static $instance = [];
    /**
     * redis连接句柄
     *
     * @var \Redis
     */
    private $handler;

    /**
     * 构造函数
     * @param array $options 缓存参数
     * @param null  $select
     * @access public
     */
    public function __construct($options = [], $select = null)
    {
        if (!empty($options)) {
            $this->options = array_merge($this->options, $options);
        }
        $func          = $this->options['persistent'] ? 'pconnect' : 'connect';
        //注意 $persistent_id 此处,持久连接设置标识
        $persistent_id = $this->options['persistent'] ? 'pconnect_' . $select : null;
        $this->handler = new \Redis;
        $this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout'], $persistent_id);
        if ('' != $this->options['password']) {
            $this->handler->auth($this->options['password']);
        }
        $this->db_index = (int)$select;
        $this->handler->select($this->db_index);
    }

    /**
     * 析构释放连接
     * @access public
     */
    public function __destruct()
    {
        self::$instance[$this->db_index]->getConnect()->close();
        self::$instance[$this->db_index] = null;
        if (isset($this->handler)) {
            $this->handler->close();
            $this->handler = null;
        }
    }

    /**
     * @return \Redis
     */
    public function getConnect()
    {
        return $this->handler;
    }

    /**
     * 获取类单例
     * @param array $options
     * @param int   $db_index
     * @return self
     */
    public static function getRedisInstance($options = [], $db_index = 0)
    {
        $db_index = (int)$db_index;
        if (!isset(self::$instance[$db_index])) {
            self::$instance[$db_index] = new self($options, $db_index);
        }
        return self::$instance[$db_index];
    }
}

///
//
$r31 = RedisAliMulti::getRedisInstance($config, 3);
$r41 = RedisAliMulti::getRedisInstance($config, 4);
$r31->getConnect()->set('33333333333===', '22222222', 600);
$r41->getConnect()->set('44444444444===', '22222222', 600);

原因说明:要给持久连接设置一个数据库标识即可,即使用某个库时候,把这个库设置一个标识

如下代码片段

//注意 $persistent_id 此处,持久接设置标识
        $persistent_id = $this->options['persistent'] ? 'pconnect_' . $select : null;
        $this->handler = new \Redis;
        $this->handler->$func($this->options['host'], $this->options['port'], $this->options['timeout'], $persistent_id);

至此完美解决

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

风.foxwho

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值