RedisEngine.php 8.6 KB

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