RedisEngine.php 6.0 KB

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