PHPRedisConnection.php
2.16 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
<?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);
}
}