forked from heyanlong/yii2-redis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Connection.php
213 lines (178 loc) · 6.06 KB
/
Connection.php
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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
<?php
/**
* @link http://www.heyanlong.com/
* @copyright Copyright (c) 2015 heyanlong.com
* @license http://www.heyanlong.com/license/
*/
namespace heyanlong\redis;
use yii\db\Exception;
use yii\helpers\Inflector;
class Connection extends \yii\redis\Connection
{
const EVENT_AFTER_OPEN = 'afterOpen';
/** @var string[] $master Parameters for connections */
public $master = [];
/** @var resource $_socket Current connection */
private $_socket;
/** @var resource[] $_sockets Store all connections, to prevent recconects */
private $_sockets = [];
/**
* @inheritdoc
*/
public function __sleep()
{
$this->close();
return array_keys(get_object_vars($this));
}
/**
* @inheritdoc
*/
public function getIsActive()
{
return $this->_socket !== null;
}
/**
* @inheritdoc
*
* Store all opened connections, to prevent recconects
*/
public function open($hostname = '')
{
if (!isset($this->_sockets[$hostname])) {
if ($this->getIsActive() && $hostname == '') {
return;
}
$hostname = $hostname == '' ? $this->master[array_rand($this->master)] : $hostname;
$this->_sockets[$hostname] = $this->connect($hostname);
}
$this->_socket = &$this->_sockets[$hostname];
}
/**
* @inheritdoc
*/
public function close()
{
if ($this->_socket !== null) {
$this->executeCommand('QUIT');
stream_socket_shutdown($this->_socket, STREAM_SHUT_RDWR);
$this->_socket = null;
}
}
/**
* @inheritdoc
*/
protected function initConnection()
{
$this->trigger(self::EVENT_AFTER_OPEN);
}
/**
* @inheritdoc
*/
public function __call($name, $params)
{
$redisCommand = strtoupper(Inflector::camel2words($name, false));
if (in_array($redisCommand, $this->redisCommands)) {
return $this->executeCommand($name, $params);
} else {
return parent::__call($name, $params);
}
}
/**
* @inheritdoc
*/
public function executeCommand($name, $params = [], $hostname = '')
{
$this->open($hostname);
array_unshift($params, $name);
$command = '*' . count($params) . "\r\n";
foreach ($params as $arg) {
$command .= '$' . mb_strlen($arg, '8bit') . "\r\n" . $arg . "\r\n";
}
\Yii::trace("Executing Redis Command: {$name}", __METHOD__);
fwrite($this->_socket, $command);
/**
* There is a bug with "implode(' ', $params)". If not standart serializer is used (e.g. igbinary) - key value may contains spaces and "\n".
* Therefore we need to pass original parameters array.
*/
return $this->parseResponse($params, $this->_socket);
}
/**
* @inheritdoc
*/
private function parseResponse($command, $socket)
{
if (($line = fgets($socket)) === false) {
throw new Exception("Failed to read from socket.\nRedis command was: " . implode(' ', $command));
}
$type = $line[0];
$line = mb_substr($line, 1, -2, '8bit');
switch ($type) {
case '+': // Status reply
if ($line === 'OK' || $line === 'PONG') {
return true;
} else {
return $line;
}
case '-': // Error reply
$moved = explode(' ', $line);
if (isset($moved[0]) && $moved[0] == 'MOVED') {
$hostname = $moved[2];
// Some tricky with array_shift - no need to create an extra variables
return $this->executeCommand(array_shift($command), $command, $hostname);
} else {
throw new Exception("Redis error: " . $line . "\nRedis command was: " . implode(' ', $command));
}
case ':': // Integer reply
// no cast to int as it is in the range of a signed 64 bit integer
return $line;
case '$': // Bulk replies
if ($line == '-1') {
return null;
}
$length = $line + 2;
$data = '';
while ($length > 0) {
if (($block = fread($socket, $length)) === false) {
throw new Exception("Failed to read from socket.\nRedis command was: " . implode(' ', $command));
}
$data .= $block;
$length -= mb_strlen($block, '8bit');
}
return mb_substr($data, 0, -2, '8bit');
case '*': // Multi-bulk replies
$count = (int)$line;
$data = [];
for ($i = 0; $i < $count; $i++) {
$data[] = $this->parseResponse($command, $socket);
}
return $data;
default:
throw new Exception('Received illegal data from redis: ' . $line . "\nRedis command was: " . implode(' ', $command));
}
}
/**
* @inheritdoc
*/
private function connect($node)
{
$socket = null;
$connection = $node . ', database=' . $this->database;
\Yii::trace('Opening redis DB connection: ' . $connection, __METHOD__);
$socket = stream_socket_client(
'tcp://' . $connection,
$errorNumber,
$errorDescription,
$this->connectionTimeout ? $this->connectionTimeout : ini_get("default_socket_timeout")
);
if ($socket) {
if ($this->dataTimeout !== null) {
stream_set_timeout($socket, $timeout = (int)$this->dataTimeout, (int)(($this->dataTimeout - $timeout) * 1000000));
}
} else {
\Yii::error("Failed to open redis DB connection ($connection): $errorNumber - $errorDescription", __CLASS__);
$message = YII_DEBUG ? "Failed to open redis DB connection ($connection): $errorNumber - $errorDescription" : 'Failed to open DB connection.';
throw new Exception($message, $errorDescription, (int)$errorNumber);
}
return $socket;
}
}