RedisEngine.php 9.1 KB

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