forked from mklooss/credis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Cluster.php
317 lines (304 loc) · 8.32 KB
/
Cluster.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
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
<?php
/**
* Credis, a Redis interface for the modest
*
* @author Justin Poliey <[email protected]>
* @copyright 2009 Justin Poliey <[email protected]>
* @license http://www.opensource.org/licenses/mit-license.php The MIT License
* @package Credis
*/
/**
* A generalized Credis_Client interface for a cluster of Redis servers
*/
class Credis_Cluster
{
/**
* Collection of Credis_Client objects attached to Redis servers
* @var Credis_Client[]
*/
protected $clients;
/**
* If a server is set as master, all write commands go to that one
* @var Credis_Client
*/
protected $masterClient;
/**
* Aliases of Credis_Client objects attached to Redis servers, used to route commands to specific servers
* @see Credis_Cluster::to
* @var array
*/
protected $aliases;
/**
* Hash ring of Redis server nodes
* @var array
*/
protected $ring;
/**
* Individual nodes of pointers to Redis servers on the hash ring
* @var array
*/
protected $nodes;
/**
* The commands that are not subject to hashing
* @var array
* @access protected
*/
protected $dont_hash;
/**
* Creates an interface to a cluster of Redis servers
* Each server should be in the format:
* array(
* 'host' => hostname,
* 'port' => port,
* 'db' => db,
* 'password' => password,
* 'timeout' => timeout,
* 'alias' => alias,
* 'persistent' => persistence_identifier,
* 'master' => master
* 'write_only'=> true/false
* )
*
* @param array $servers The Redis servers in the cluster.
* @param int $replicas
* @param bool $standAlone
*/
public function __construct($servers, $replicas = 128, $standAlone = false)
{
$this->clients = array();
$this->masterClient = null;
$this->aliases = array();
$this->ring = array();
$this->replicas = (int)$replicas;
$client = null;
foreach ($servers as $server)
{
if(is_array($server)){
$client = new Credis_Client(
$server['host'],
$server['port'],
isset($server['timeout']) ? $server['timeout'] : 2.5,
isset($server['persistent']) ? $server['persistent'] : '',
isset($server['db']) ? $server['db'] : 0,
isset($server['password']) ? $server['password'] : null
);
if (isset($server['alias'])) {
$this->aliases[$server['alias']] = $client;
}
if(isset($server['master']) && $server['master'] === true){
$this->masterClient = $client;
if(isset($server['write_only']) && $server['write_only'] === true){
continue;
}
}
} elseif($server instanceof Credis_Client){
$client = $server;
} else {
throw new CredisException('Server should either be an array or an instance of Credis_Client');
}
if($standAlone) {
$client->forceStandalone();
}
$this->clients[] = $client;
for ($replica = 0; $replica <= $this->replicas; $replica++) {
$md5num = hexdec(substr(md5($client->getHost().':'.$client->getPort().'-'.$replica),0,7));
$this->ring[$md5num] = count($this->clients)-1;
}
}
ksort($this->ring, SORT_NUMERIC);
$this->nodes = array_keys($this->ring);
$this->dont_hash = array_flip(array(
'RANDOMKEY', 'DBSIZE', 'PIPELINE', 'EXEC',
'SELECT', 'MOVE', 'FLUSHDB', 'FLUSHALL',
'SAVE', 'BGSAVE', 'LASTSAVE', 'SHUTDOWN',
'INFO', 'MONITOR', 'SLAVEOF'
));
if($this->masterClient !== null && count($this->clients()) == 0){
$this->clients[] = $this->masterClient;
for ($replica = 0; $replica <= $this->replicas; $replica++) {
$md5num = hexdec(substr(md5($this->masterClient->getHost().':'.$this->masterClient->getHost().'-'.$replica),0,7));
$this->ring[$md5num] = count($this->clients)-1;
}
$this->nodes = array_keys($this->ring);
}
}
/**
* @param Credis_Client $masterClient
* @param bool $writeOnly
* @return Credis_Cluster
*/
public function setMasterClient(Credis_Client $masterClient, $writeOnly=false)
{
if(!$masterClient instanceof Credis_Client){
throw new CredisException('Master client should be an instance of Credis_Client');
}
$this->masterClient = $masterClient;
if (!isset($this->aliases['master'])) {
$this->aliases['master'] = $masterClient;
}
if(!$writeOnly){
$this->clients[] = $this->masterClient;
for ($replica = 0; $replica <= $this->replicas; $replica++) {
$md5num = hexdec(substr(md5($this->masterClient->getHost().':'.$this->masterClient->getHost().'-'.$replica),0,7));
$this->ring[$md5num] = count($this->clients)-1;
}
$this->nodes = array_keys($this->ring);
}
return $this;
}
/**
* Get a client by index or alias.
*
* @param string|int $alias
* @throws CredisException
* @return Credis_Client
*/
public function client($alias)
{
if (is_int($alias) && isset($this->clients[$alias])) {
return $this->clients[$alias];
}
else if (isset($this->aliases[$alias])) {
return $this->aliases[$alias];
}
throw new CredisException("Client $alias does not exist.");
}
/**
* Get an array of all clients
*
* @return array|Credis_Client[]
*/
public function clients()
{
return $this->clients;
}
/**
* Execute a command on all clients
*
* @return array
*/
public function all()
{
$args = func_get_args();
$name = array_shift($args);
$results = array();
foreach($this->clients as $client) {
$results[] = $client->__call($name, $args);
}
return $results;
}
/**
* Get the client that the key would hash to.
*
* @param string $key
* @return \Credis_Client
*/
public function byHash($key)
{
return $this->clients[$this->hash($key)];
}
/**
* Execute a Redis command on the cluster with automatic consistent hashing and read/write splitting
*
* @param string $name
* @param array $args
* @return mixed
*/
public function __call($name, $args)
{
if($this->masterClient !== null && !$this->isReadOnlyCommand($name)){
$client = $this->masterClient;
}elseif (count($this->clients()) == 1 || isset($this->dont_hash[strtoupper($name)]) || !isset($args[0])) {
$client = $this->clients[0];
}
else {
$client = $this->byHash($args[0]);
}
return $client->__call($name, $args);
}
/**
* Get client index for a key by searching ring with binary search
*
* @param string $key The key to hash
* @return int The index of the client object associated with the hash of the key
*/
public function hash($key)
{
$needle = hexdec(substr(md5($key),0,7));
$server = $min = 0;
$max = count($this->nodes) - 1;
while ($max >= $min) {
$position = (int) (($min + $max) / 2);
$server = $this->nodes[$position];
if ($needle < $server) {
$max = $position - 1;
}
else if ($needle > $server) {
$min = $position + 1;
}
else {
break;
}
}
return $this->ring[$server];
}
public function isReadOnlyCommand($command)
{
$readOnlyCommands = array(
'DBSIZE',
'INFO',
'MONITOR',
'EXISTS',
'TYPE',
'KEYS',
'SCAN',
'RANDOMKEY',
'TTL',
'GET',
'MGET',
'SUBSTR',
'STRLEN',
'GETRANGE',
'GETBIT',
'LLEN',
'LRANGE',
'LINDEX',
'SCARD',
'SISMEMBER',
'SINTER',
'SUNION',
'SDIFF',
'SMEMBERS',
'SSCAN',
'SRANDMEMBER',
'ZRANGE',
'ZREVRANGE',
'ZRANGEBYSCORE',
'ZREVRANGEBYSCORE',
'ZCARD',
'ZSCORE',
'ZCOUNT',
'ZRANK',
'ZREVRANK',
'ZSCAN',
'HGET',
'HMGET',
'HEXISTS',
'HLEN',
'HKEYS',
'HVALS',
'HGETALL',
'HSCAN',
'PING',
'AUTH',
'SELECT',
'ECHO',
'QUIT',
'OBJECT',
'BITCOUNT',
'TIME',
'SORT'
);
return in_array(strtoupper($command),$readOnlyCommands);
}
}