RedisEngine.php 6.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231
  1. <?php
  2. /**
  3. * Redis storage engine for cache
  4. *
  5. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  6. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  7. *
  8. * Licensed under The MIT License
  9. * For full copyright and license information, please see the LICENSE.txt
  10. * Redistributions of files must retain the above copyright notice.
  11. *
  12. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  13. * @link http://cakephp.org CakePHP(tm) Project
  14. * @package Cake.Cache.Engine
  15. * @since CakePHP(tm) v 2.2
  16. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  17. */
  18. /**
  19. * Redis storage engine for cache.
  20. *
  21. * @package Cake.Cache.Engine
  22. */
  23. class RedisEngine extends CacheEngine {
  24. /**
  25. * Redis wrapper.
  26. *
  27. * @var Redis
  28. */
  29. protected $_Redis = null;
  30. /**
  31. * Settings
  32. *
  33. * - server = string URL or ip to the Redis server host
  34. * - database = integer database number to use for connection
  35. * - port = integer port number to the Redis server (default: 6379)
  36. * - timeout = float timeout in seconds (default: 0)
  37. * - persistent = boolean Connects to the Redis server with a persistent connection (default: true)
  38. * - unix_socket = path to the unix socket file (default: false)
  39. *
  40. * @var array
  41. */
  42. public $settings = array();
  43. /**
  44. * Initialize the Cache Engine
  45. *
  46. * Called automatically by the cache frontend
  47. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  48. *
  49. * @param array $settings array of setting for the engine
  50. * @return boolean True if the engine has been successfully initialized, false if not
  51. */
  52. public function init($settings = array()) {
  53. if (!class_exists('Redis')) {
  54. return false;
  55. }
  56. parent::init(array_merge(array(
  57. 'engine' => 'Redis',
  58. 'prefix' => null,
  59. 'server' => '127.0.0.1',
  60. 'database' => 0,
  61. 'port' => 6379,
  62. 'password' => false,
  63. 'timeout' => 0,
  64. 'persistent' => true,
  65. 'unix_socket' => false
  66. ), $settings)
  67. );
  68. return $this->_connect();
  69. }
  70. /**
  71. * Connects to a Redis server
  72. *
  73. * @return boolean True if Redis server was connected
  74. */
  75. protected function _connect() {
  76. $return = false;
  77. try {
  78. $this->_Redis = new Redis();
  79. if (!empty($this->settings['unix_socket'])) {
  80. $return = $this->_Redis->connect($this->settings['unix_socket']);
  81. } elseif (empty($this->settings['persistent'])) {
  82. $return = $this->_Redis->connect($this->settings['server'], $this->settings['port'], $this->settings['timeout']);
  83. } else {
  84. $persistentId = $this->settings['port'] . $this->settings['timeout'] . $this->settings['database'];
  85. $return = $this->_Redis->pconnect($this->settings['server'], $this->settings['port'], $this->settings['timeout'], $persistentId);
  86. }
  87. } catch (RedisException $e) {
  88. return false;
  89. }
  90. if ($return && $this->settings['password']) {
  91. $return = $this->_Redis->auth($this->settings['password']);
  92. }
  93. if ($return) {
  94. $return = $this->_Redis->select($this->settings['database']);
  95. }
  96. return $return;
  97. }
  98. /**
  99. * Write data for key into cache.
  100. *
  101. * @param string $key Identifier for the data
  102. * @param mixed $value Data to be cached
  103. * @param integer $duration How long to cache the data, in seconds
  104. * @return boolean True if the data was successfully cached, false on failure
  105. */
  106. public function write($key, $value, $duration) {
  107. if (!is_int($value)) {
  108. $value = serialize($value);
  109. }
  110. if ($duration === 0) {
  111. return $this->_Redis->set($key, $value);
  112. }
  113. return $this->_Redis->setex($key, $duration, $value);
  114. }
  115. /**
  116. * Read a key from the cache
  117. *
  118. * @param string $key Identifier for the data
  119. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  120. */
  121. public function read($key) {
  122. $value = $this->_Redis->get($key);
  123. if (ctype_digit($value)) {
  124. $value = (int)$value;
  125. }
  126. if ($value !== false && is_string($value)) {
  127. $value = unserialize($value);
  128. }
  129. return $value;
  130. }
  131. /**
  132. * Increments the value of an integer cached key
  133. *
  134. * @param string $key Identifier for the data
  135. * @param integer $offset How much to increment
  136. * @return New incremented value, false otherwise
  137. * @throws CacheException when you try to increment with compress = true
  138. */
  139. public function increment($key, $offset = 1) {
  140. return (int)$this->_Redis->incrBy($key, $offset);
  141. }
  142. /**
  143. * Decrements the value of an integer cached key
  144. *
  145. * @param string $key Identifier for the data
  146. * @param integer $offset How much to subtract
  147. * @return New decremented value, false otherwise
  148. * @throws CacheException when you try to decrement with compress = true
  149. */
  150. public function decrement($key, $offset = 1) {
  151. return (int)$this->_Redis->decrBy($key, $offset);
  152. }
  153. /**
  154. * Delete a key from the cache
  155. *
  156. * @param string $key Identifier for the data
  157. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  158. */
  159. public function delete($key) {
  160. return $this->_Redis->delete($key) > 0;
  161. }
  162. /**
  163. * Delete all keys from the cache
  164. *
  165. * @param boolean $check Whether or not expiration keys should be checked. If
  166. * true, no keys will be removed as cache will rely on redis TTL's.
  167. * @return boolean True if the cache was successfully cleared, false otherwise
  168. */
  169. public function clear($check) {
  170. if ($check) {
  171. return true;
  172. }
  173. $keys = $this->_Redis->getKeys($this->settings['prefix'] . '*');
  174. $this->_Redis->del($keys);
  175. return true;
  176. }
  177. /**
  178. * Returns the `group value` for each of the configured groups
  179. * If the group initial value was not found, then it initializes
  180. * the group accordingly.
  181. *
  182. * @return array
  183. */
  184. public function groups() {
  185. $result = array();
  186. foreach ($this->settings['groups'] as $group) {
  187. $value = $this->_Redis->get($this->settings['prefix'] . $group);
  188. if (!$value) {
  189. $value = 1;
  190. $this->_Redis->set($this->settings['prefix'] . $group, $value);
  191. }
  192. $result[] = $group . $value;
  193. }
  194. return $result;
  195. }
  196. /**
  197. * Increments the group value to simulate deletion of all keys under a group
  198. * old values will remain in storage until they expire.
  199. *
  200. * @param string $group The group name to clear.
  201. * @return boolean success
  202. */
  203. public function clearGroup($group) {
  204. return (bool)$this->_Redis->incr($this->settings['prefix'] . $group);
  205. }
  206. /**
  207. * Disconnects from the redis server
  208. */
  209. public function __destruct() {
  210. if (!$this->settings['persistent']) {
  211. $this->_Redis->close();
  212. }
  213. }
  214. }