-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathRedisCluster.php
More file actions
371 lines (330 loc) · 8.2 KB
/
RedisCluster.php
File metadata and controls
371 lines (330 loc) · 8.2 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
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
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
<?php
/**
* Created by PhpStorm.
* User: snail
* Date: 2017/8/3
* Time: 下午3:10
*/
namespace com\pindakong\tp5ext\driver\cache;
use think\cache\Driver;
/**使用phpredis
* https://github.com/phpredis/phpredis/blob/feature/redis_cluster/cluster.markdown
* Class RedisCluster
*
* @package com\pindakong\tp5ext\driver\cache
*/
class RedisCluster extends Driver
{
/**
* @var array
*/
protected $options = [
//主机或IP,如192.168.0.110,192.168.0.110
'host' => '127.0.0.1',//slave host
//端口,如7001,7002,7003
'port' => 6379,
//链接超时时间
'timeout' => 1.5,
//读取超时时间
'read_timeout' => 1.5,
//过期时间
'expire' => 0,
//持久化链接
'persistent' => false,
//缓存前缀
'prefix' => '',
//是否需要json序列化
'serialize' => true,
// 是否需要断线重连
'break_reconnect' => true,
//最大重试连接次数
'max_reconnect_times' => 20,
];
/**
* @var array
*/
private static $node_params = [];
/**需要重连的错误信息
*
* @var array
*/
private $breakMatchStr = [
'Connection refused',
];
/**
* 架构函数
*
* @access public
*
* @param array $options 缓存参数
*
* @throws \Exception
*/
public function __construct($options = [])
{
if (!extension_loaded('redis'))
{
throw new \BadFunctionCallException('not support: redis');
}
if (!empty($options))
{
$this->options = array_merge($this->options, $options);
}
$this->init_connect();
}
/**
* @param int $reconnect_times 重连次数
*
* @throws \Exception
*/
protected function init_connect($reconnect_times = 0)
{
//此处进行分布式配置
$params = array(
'hosts' => explode(',', $this->options['host']),
'ports' => explode(',', $this->options['port']),
);
//拼接参数
$hostsNum = count($params['hosts']);
$seeds = [];
for ($i = 0; $i < $hostsNum; $i++)
{
$host = $params['hosts'][$i];
$port = $params['ports'][$i] ? $params['ports'][$i] : $params['ports'][0];
$seeds[$i] = $host . ":" . $port;
}
try
{
//连接并指定timeout和read_timeout
$this->handler = new \RedisCluster(NULL, $seeds, $this->options["timeout"], $this->options["read_timeout"], $this->options["persistent"]);
// 始终在主机和从机之间随机分配只读命令
$this->handler->setOption(\RedisCluster::OPT_SLAVE_FAILOVER, \RedisCluster::FAILOVER_DISTRIBUTE);
}
catch (\Exception $e)
{
if ($this->isBreak($e))
{
if ($reconnect_times <= $this->options['max_reconnect_times'])
{
echo $reconnect_times . "<br/>";
sleep(0.5);
$this->init_connect(++$reconnect_times);
}
else
{
throw $e;
}
}
else
{
throw $e;
}
}
}
/**是否断线
*
* @param \Exception $e
*
* @return bool
*/
protected function isBreak(\Exception $e)
{
if (!$this->options['break_reconnect'])
{
return false;
}
$error = $e->getMessage();
foreach ($this->breakMatchStr as $msg)
{
if (false !== stripos($error, $msg))
{
return true;
}
}
return false;
}
/**
* 判断缓存是否存在
*
* @access public
*
* @param string $name 缓存变量名
*
* @return bool
*/
public function has($name)
{
// TODO: Implement has() method.
return $this->handler->exists($this->getCacheKey($name));
}
/**
* 读取缓存
*
* @access public
*
* @param string $name 缓存变量名
* @param mixed $default 默认值
*
* @return mixed
*/
public function get($name, $default = false)
{
// TODO: Implement get() method.
$this->readTimes++;
$value = $this->handler->get($this->getCacheKey($name));
if (is_null($value) || false === $value)
{
return $default;
}
return $this->unserialize($value);
}
/**
* 写入缓存
*
* @access public
*
* @param string $name 缓存变量名
* @param mixed $value 存储数据
* @param int $expire 有效时间 0为永久
*
* @return boolean
*/
public function set($name, $value, $expire = null)
{
// TODO: Implement set() method.
$this->writeTimes++;
if (is_null($expire))
{
$expire = $this->options['expire'];
}
if ($this->tag && !$this->has($name))
{
$first = true;
}
$key = $this->getCacheKey($name);
$expire = $this->getExpireTime($expire);
$value = $this->serialize($value);
if ($expire)
{
$result = $this->handler->setex($key, $expire, $value);
}
else
{
$result = $this->handler->set($key, $value);
}
isset($first) && $this->setTagItem($key);
return $result;
}
/**
* 自增缓存(针对数值缓存)
*
* @access public
*
* @param string $name 缓存变量名
* @param int $step 步长
*
* @return false|int
*/
public function inc($name, $step = 1)
{
// TODO: Implement inc() method.
$this->writeTimes++;
$key = $this->getCacheKey($name);
return $this->handler->incrby($key, $step);
}
/**
* 自减缓存(针对数值缓存)
*
* @access public
*
* @param string $name 缓存变量名
* @param int $step 步长
*
* @return false|int
*/
public function dec($name, $step = 1)
{
// TODO: Implement dec() method.
$this->writeTimes++;
$key = $this->getCacheKey($name);
return $this->handler->decrby($key, $step);
}
/**
* 删除缓存
*
* @access public
*
* @param string $name 缓存变量名
*
* @return boolean
*/
public function rm($name)
{
// TODO: Implement rm() method.
$this->writeTimes++;
return $this->handler->del($this->getCacheKey($name));
}
/**
* 清除缓存
*
* @access public
*
* @param string $tag 标签名
*
* @return boolean
*/
public function clear($tag = null)
{
// TODO: Implement clear() method.
if ($tag)
{
// 指定标签清除
$keys = $this->getTagItem($tag);
foreach ($keys as $key)
{
$this->handler->del($key);
}
$this->rm('tag_' . md5($tag));
return true;
}
$this->writeTimes++;
return $this->handler->flushDB(self::$node_params);
}
/**
* 序列化数据
*
* @access protected
*
* @param mixed $data
*
* @return string
*/
protected function serialize($data)
{
if (is_scalar($data) || !$this->options['serialize'])
{
return $data;
}
return self::$serialize[2] . json_encode($data);
}
/**
* 反序列化数据
*
* @access protected
*
* @param string $data
*
* @return mixed
*/
protected function unserialize($data)
{
if ($this->options['serialize'] && 0 === strpos($data, self::$serialize[2]))
{
return json_decode((substr($data, self::$serialize[3])), true);
}
else
{
return $data;
}
}
}