-
Notifications
You must be signed in to change notification settings - Fork 3.4k
/
RedisEngine.php
407 lines (357 loc) · 12.2 KB
/
RedisEngine.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
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
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
<?php
declare(strict_types=1);
/**
* CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
* Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
*
* Licensed under The MIT License
* For full copyright and license information, please see the LICENSE.txt
* Redistributions of files must retain the above copyright notice.
*
* @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
* @link https://cakephp.org CakePHP(tm) Project
* @since 2.2.0
* @license https://opensource.org/licenses/mit-license.php MIT License
*/
namespace Cake\Cache\Engine;
use Cake\Cache\CacheEngine;
use Cake\Core\Exception\CakeException;
use Cake\Log\Log;
use DateInterval;
use Redis;
use RedisException;
/**
* Redis storage engine for cache.
*/
class RedisEngine extends CacheEngine
{
/**
* Redis wrapper.
*
* @var \Redis
*/
protected Redis $_Redis;
/**
* The default config used unless overridden by runtime configuration
*
* - `database` database number to use for connection.
* - `duration` Specify how long items in this cache configuration last.
* - `groups` List of groups or 'tags' associated to every key stored in this config.
* handy for deleting a complete group from cache.
* - `password` Redis server password.
* - `persistent` Connect to the Redis server with a persistent connection
* - `port` port number to the Redis server.
* - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
* with either another cache config or another application.
* - `scanCount` Number of keys to ask for each scan (default: 10)
* - `server` URL or IP to the Redis server host.
* - `timeout` timeout in seconds (float).
* - `unix_socket` Path to the unix socket file (default: false)
*
* @var array<string, mixed>
*/
protected array $_defaultConfig = [
'database' => 0,
'duration' => 3600,
'groups' => [],
'password' => false,
'persistent' => true,
'port' => 6379,
'prefix' => 'cake_',
'host' => null,
'server' => '127.0.0.1',
'timeout' => 0,
'unix_socket' => false,
'scanCount' => 10,
];
/**
* Initialize the Cache Engine
*
* Called automatically by the cache frontend
*
* @param array<string, mixed> $config array of setting for the engine
* @return bool True if the engine has been successfully initialized, false if not
*/
public function init(array $config = []): bool
{
if (!extension_loaded('redis')) {
throw new CakeException('The `redis` extension must be enabled to use RedisEngine.');
}
if (!empty($config['host'])) {
$config['server'] = $config['host'];
}
parent::init($config);
return $this->_connect();
}
/**
* Connects to a Redis server
*
* @return bool True if Redis server was connected
*/
protected function _connect(): bool
{
try {
$this->_Redis = new Redis();
if (!empty($this->_config['unix_socket'])) {
$return = $this->_Redis->connect($this->_config['unix_socket']);
} elseif (empty($this->_config['persistent'])) {
$return = $this->_Redis->connect(
$this->_config['server'],
(int)$this->_config['port'],
(int)$this->_config['timeout']
);
} else {
$persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database'];
$return = $this->_Redis->pconnect(
$this->_config['server'],
(int)$this->_config['port'],
(int)$this->_config['timeout'],
$persistentId
);
}
} catch (RedisException $e) {
if (class_exists(Log::class)) {
Log::error('RedisEngine could not connect. Got error: ' . $e->getMessage());
}
return false;
}
if ($return && $this->_config['password']) {
$return = $this->_Redis->auth($this->_config['password']);
}
if ($return) {
$return = $this->_Redis->select((int)$this->_config['database']);
}
return $return;
}
/**
* Write data for key into cache.
*
* @param string $key Identifier for the data
* @param mixed $value Data to be cached
* @param \DateInterval|int|null $ttl Optional. The TTL value of this item. If no value is sent and
* the driver supports TTL then the library may set a default value
* for it or let the driver take care of that.
* @return bool True if the data was successfully cached, false on failure
*/
public function set(string $key, mixed $value, DateInterval|int|null $ttl = null): bool
{
$key = $this->_key($key);
$value = $this->serialize($value);
$duration = $this->duration($ttl);
if ($duration === 0) {
return $this->_Redis->set($key, $value);
}
return $this->_Redis->setEx($key, $duration, $value);
}
/**
* Read a key from the cache
*
* @param string $key Identifier for the data
* @param mixed $default Default value to return if the key does not exist.
* @return mixed The cached data, or the default if the data doesn't exist, has
* expired, or if there was an error fetching it
*/
public function get(string $key, mixed $default = null): mixed
{
$value = $this->_Redis->get($this->_key($key));
if ($value === false) {
return $default;
}
return $this->unserialize($value);
}
/**
* Increments the value of an integer cached key & update the expiry time
*
* @param string $key Identifier for the data
* @param int $offset How much to increment
* @return int|false New incremented value, false otherwise
*/
public function increment(string $key, int $offset = 1): int|false
{
$duration = $this->_config['duration'];
$key = $this->_key($key);
$value = $this->_Redis->incrBy($key, $offset);
if ($duration > 0) {
$this->_Redis->expire($key, $duration);
}
return $value;
}
/**
* Decrements the value of an integer cached key & update the expiry time
*
* @param string $key Identifier for the data
* @param int $offset How much to subtract
* @return int|false New decremented value, false otherwise
*/
public function decrement(string $key, int $offset = 1): int|false
{
$duration = $this->_config['duration'];
$key = $this->_key($key);
$value = $this->_Redis->decrBy($key, $offset);
if ($duration > 0) {
$this->_Redis->expire($key, $duration);
}
return $value;
}
/**
* Delete a key from the cache
*
* @param string $key Identifier for the data
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
*/
public function delete(string $key): bool
{
$key = $this->_key($key);
return (int)$this->_Redis->del($key) > 0;
}
/**
* Delete a key from the cache asynchronously
*
* Just unlink a key from the cache. The actual removal will happen later asynchronously.
*
* @param string $key Identifier for the data
* @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
*/
public function deleteAsync(string $key): bool
{
$key = $this->_key($key);
return (int)$this->_Redis->unlink($key) > 0;
}
/**
* Delete all keys from the cache
*
* @return bool True if the cache was successfully cleared, false otherwise
*/
public function clear(): bool
{
$this->_Redis->setOption(Redis::OPT_SCAN, (string)Redis::SCAN_RETRY);
$isAllDeleted = true;
$iterator = null;
$pattern = $this->_config['prefix'] . '*';
while (true) {
$keys = $this->_Redis->scan($iterator, $pattern, (int)$this->_config['scanCount']);
if ($keys === false) {
break;
}
foreach ($keys as $key) {
$isDeleted = ((int)$this->_Redis->del($key) > 0);
$isAllDeleted = $isAllDeleted && $isDeleted;
}
}
return $isAllDeleted;
}
/**
* Delete all keys from the cache by a blocking operation
*
* Faster than clear() using unlink method.
*
* @return bool True if the cache was successfully cleared, false otherwise
*/
public function clearBlocking(): bool
{
$this->_Redis->setOption(Redis::OPT_SCAN, (string)Redis::SCAN_RETRY);
$isAllDeleted = true;
$iterator = null;
$pattern = $this->_config['prefix'] . '*';
while (true) {
$keys = $this->_Redis->scan($iterator, $pattern, (int)$this->_config['scanCount']);
if ($keys === false) {
break;
}
foreach ($keys as $key) {
$isDeleted = ((int)$this->_Redis->unlink($key) > 0);
$isAllDeleted = $isAllDeleted && $isDeleted;
}
}
return $isAllDeleted;
}
/**
* Write data for key into cache if it doesn't exist already.
* If it already exists, it fails and returns false.
*
* @param string $key Identifier for the data.
* @param mixed $value Data to be cached.
* @return bool True if the data was successfully cached, false on failure.
* @link https://github.com/phpredis/phpredis#set
*/
public function add(string $key, mixed $value): bool
{
$duration = $this->_config['duration'];
$key = $this->_key($key);
$value = $this->serialize($value);
if ($this->_Redis->set($key, $value, ['nx', 'ex' => $duration])) {
return true;
}
return false;
}
/**
* Returns the `group value` for each of the configured groups
* If the group initial value was not found, then it initializes
* the group accordingly.
*
* @return array<string>
*/
public function groups(): array
{
$result = [];
foreach ($this->_config['groups'] as $group) {
$value = $this->_Redis->get($this->_config['prefix'] . $group);
if (!$value) {
$value = $this->serialize(1);
$this->_Redis->set($this->_config['prefix'] . $group, $value);
}
$result[] = $group . $value;
}
return $result;
}
/**
* Increments the group value to simulate deletion of all keys under a group
* old values will remain in storage until they expire.
*
* @param string $group name of the group to be cleared
* @return bool success
*/
public function clearGroup(string $group): bool
{
return (bool)$this->_Redis->incr($this->_config['prefix'] . $group);
}
/**
* Serialize value for saving to Redis.
*
* This is needed instead of using Redis' in built serialization feature
* as it creates problems incrementing/decrementing intially set integer value.
*
* @param mixed $value Value to serialize.
* @return string
* @link https://github.com/phpredis/phpredis/issues/81
*/
protected function serialize(mixed $value): string
{
if (is_int($value)) {
return (string)$value;
}
return serialize($value);
}
/**
* Unserialize string value fetched from Redis.
*
* @param string $value Value to unserialize.
* @return mixed
*/
protected function unserialize(string $value): mixed
{
if (preg_match('/^[-]?\d+$/', $value)) {
return (int)$value;
}
return unserialize($value);
}
/**
* Disconnects from the redis server
*/
public function __destruct()
{
if (empty($this->_config['persistent'])) {
$this->_Redis->close();
}
}
}