1: <?php
2: /**
3: * CakePHP(tm) : Rapid Development Framework (https://cakephp.org)
4: * Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
5: *
6: * Licensed under The MIT License
7: * For full copyright and license information, please see the LICENSE.txt
8: * Redistributions of files must retain the above copyright notice.
9: *
10: * @copyright Copyright (c) Cake Software Foundation, Inc. (https://cakefoundation.org)
11: * @link https://cakephp.org CakePHP(tm) Project
12: * @since 2.2.0
13: * @license https://opensource.org/licenses/mit-license.php MIT License
14: */
15:
16: namespace Cake\Cache\Engine;
17:
18: use Cake\Cache\CacheEngine;
19: use Redis;
20: use RedisException;
21:
22: /**
23: * Redis storage engine for cache.
24: */
25: class RedisEngine extends CacheEngine
26: {
27: /**
28: * Redis wrapper.
29: *
30: * @var \Redis
31: */
32: protected $_Redis;
33:
34: /**
35: * The default config used unless overridden by runtime configuration
36: *
37: * - `database` database number to use for connection.
38: * - `duration` Specify how long items in this cache configuration last.
39: * - `groups` List of groups or 'tags' associated to every key stored in this config.
40: * handy for deleting a complete group from cache.
41: * - `password` Redis server password.
42: * - `persistent` Connect to the Redis server with a persistent connection
43: * - `port` port number to the Redis server.
44: * - `prefix` Prefix appended to all entries. Good for when you need to share a keyspace
45: * with either another cache config or another application.
46: * - `probability` Probability of hitting a cache gc cleanup. Setting to 0 will disable
47: * cache::gc from ever being called automatically.
48: * - `server` URL or ip to the Redis server host.
49: * - `timeout` timeout in seconds (float).
50: * - `unix_socket` Path to the unix socket file (default: false)
51: *
52: * @var array
53: */
54: protected $_defaultConfig = [
55: 'database' => 0,
56: 'duration' => 3600,
57: 'groups' => [],
58: 'password' => false,
59: 'persistent' => true,
60: 'port' => 6379,
61: 'prefix' => 'cake_',
62: 'probability' => 100,
63: 'host' => null,
64: 'server' => '127.0.0.1',
65: 'timeout' => 0,
66: 'unix_socket' => false,
67: ];
68:
69: /**
70: * Initialize the Cache Engine
71: *
72: * Called automatically by the cache frontend
73: *
74: * @param array $config array of setting for the engine
75: * @return bool True if the engine has been successfully initialized, false if not
76: */
77: public function init(array $config = [])
78: {
79: if (!extension_loaded('redis')) {
80: return false;
81: }
82:
83: if (!empty($config['host'])) {
84: $config['server'] = $config['host'];
85: }
86:
87: parent::init($config);
88:
89: return $this->_connect();
90: }
91:
92: /**
93: * Connects to a Redis server
94: *
95: * @return bool True if Redis server was connected
96: */
97: protected function _connect()
98: {
99: try {
100: $this->_Redis = new Redis();
101: if (!empty($this->_config['unix_socket'])) {
102: $return = $this->_Redis->connect($this->_config['unix_socket']);
103: } elseif (empty($this->_config['persistent'])) {
104: $return = $this->_Redis->connect($this->_config['server'], $this->_config['port'], $this->_config['timeout']);
105: } else {
106: $persistentId = $this->_config['port'] . $this->_config['timeout'] . $this->_config['database'];
107: $return = $this->_Redis->pconnect($this->_config['server'], $this->_config['port'], $this->_config['timeout'], $persistentId);
108: }
109: } catch (RedisException $e) {
110: return false;
111: }
112: if ($return && $this->_config['password']) {
113: $return = $this->_Redis->auth($this->_config['password']);
114: }
115: if ($return) {
116: $return = $this->_Redis->select($this->_config['database']);
117: }
118:
119: return $return;
120: }
121:
122: /**
123: * Write data for key into cache.
124: *
125: * @param string $key Identifier for the data
126: * @param mixed $value Data to be cached
127: * @return bool True if the data was successfully cached, false on failure
128: */
129: public function write($key, $value)
130: {
131: $key = $this->_key($key);
132:
133: if (!is_int($value)) {
134: $value = serialize($value);
135: }
136:
137: $duration = $this->_config['duration'];
138: if ($duration === 0) {
139: return $this->_Redis->set($key, $value);
140: }
141:
142: return $this->_Redis->setEx($key, $duration, $value);
143: }
144:
145: /**
146: * Read a key from the cache
147: *
148: * @param string $key Identifier for the data
149: * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
150: */
151: public function read($key)
152: {
153: $key = $this->_key($key);
154:
155: $value = $this->_Redis->get($key);
156: if (preg_match('/^[-]?\d+$/', $value)) {
157: return (int)$value;
158: }
159: if ($value !== false && is_string($value)) {
160: return unserialize($value);
161: }
162:
163: return $value;
164: }
165:
166: /**
167: * Increments the value of an integer cached key & update the expiry time
168: *
169: * @param string $key Identifier for the data
170: * @param int $offset How much to increment
171: * @return int|false New incremented value, false otherwise
172: */
173: public function increment($key, $offset = 1)
174: {
175: $duration = $this->_config['duration'];
176: $key = $this->_key($key);
177:
178: $value = (int)$this->_Redis->incrBy($key, $offset);
179: if ($duration > 0) {
180: $this->_Redis->expire($key, $duration);
181: }
182:
183: return $value;
184: }
185:
186: /**
187: * Decrements the value of an integer cached key & update the expiry time
188: *
189: * @param string $key Identifier for the data
190: * @param int $offset How much to subtract
191: * @return int|false New decremented value, false otherwise
192: */
193: public function decrement($key, $offset = 1)
194: {
195: $duration = $this->_config['duration'];
196: $key = $this->_key($key);
197:
198: $value = (int)$this->_Redis->decrBy($key, $offset);
199: if ($duration > 0) {
200: $this->_Redis->expire($key, $duration);
201: }
202:
203: return $value;
204: }
205:
206: /**
207: * Delete a key from the cache
208: *
209: * @param string $key Identifier for the data
210: * @return bool True if the value was successfully deleted, false if it didn't exist or couldn't be removed
211: */
212: public function delete($key)
213: {
214: $key = $this->_key($key);
215:
216: return $this->_Redis->del($key) > 0;
217: }
218:
219: /**
220: * Delete all keys from the cache
221: *
222: * @param bool $check If true will check expiration, otherwise delete all.
223: * @return bool True if the cache was successfully cleared, false otherwise
224: */
225: public function clear($check)
226: {
227: if ($check) {
228: return true;
229: }
230:
231: $this->_Redis->setOption(Redis::OPT_SCAN, Redis::SCAN_RETRY);
232:
233: $isAllDeleted = true;
234: $iterator = null;
235: $pattern = $this->_config['prefix'] . '*';
236:
237: while (true) {
238: $keys = $this->_Redis->scan($iterator, $pattern);
239:
240: if ($keys === false) {
241: break;
242: }
243:
244: foreach ($keys as $key) {
245: $isDeleted = ($this->_Redis->del($key) > 0);
246: $isAllDeleted = $isAllDeleted && $isDeleted;
247: }
248: }
249:
250: return $isAllDeleted;
251: }
252:
253: /**
254: * Write data for key into cache if it doesn't exist already.
255: * If it already exists, it fails and returns false.
256: *
257: * @param string $key Identifier for the data.
258: * @param mixed $value Data to be cached.
259: * @return bool True if the data was successfully cached, false on failure.
260: * @link https://github.com/phpredis/phpredis#set
261: */
262: public function add($key, $value)
263: {
264: $duration = $this->_config['duration'];
265: $key = $this->_key($key);
266:
267: if (!is_int($value)) {
268: $value = serialize($value);
269: }
270:
271: if ($this->_Redis->set($key, $value, ['nx', 'ex' => $duration])) {
272: return true;
273: }
274:
275: return false;
276: }
277:
278: /**
279: * Returns the `group value` for each of the configured groups
280: * If the group initial value was not found, then it initializes
281: * the group accordingly.
282: *
283: * @return array
284: */
285: public function groups()
286: {
287: $result = [];
288: foreach ($this->_config['groups'] as $group) {
289: $value = $this->_Redis->get($this->_config['prefix'] . $group);
290: if (!$value) {
291: $value = 1;
292: $this->_Redis->set($this->_config['prefix'] . $group, $value);
293: }
294: $result[] = $group . $value;
295: }
296:
297: return $result;
298: }
299:
300: /**
301: * Increments the group value to simulate deletion of all keys under a group
302: * old values will remain in storage until they expire.
303: *
304: * @param string $group name of the group to be cleared
305: * @return bool success
306: */
307: public function clearGroup($group)
308: {
309: return (bool)$this->_Redis->incr($this->_config['prefix'] . $group);
310: }
311:
312: /**
313: * Disconnects from the redis server
314: */
315: public function __destruct()
316: {
317: if (empty($this->_config['persistent']) && $this->_Redis instanceof Redis) {
318: $this->_Redis->close();
319: }
320: }
321: }
322: