Cache_redis.php 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330
  1. <?php
  2. /**
  3. * CodeIgniter
  4. *
  5. * An open source application development framework for PHP
  6. *
  7. * This content is released under the MIT License (MIT)
  8. *
  9. * Copyright (c) 2014 - 2019, British Columbia Institute of Technology
  10. *
  11. * Permission is hereby granted, free of charge, to any person obtaining a copy
  12. * of this software and associated documentation files (the "Software"), to deal
  13. * in the Software without restriction, including without limitation the rights
  14. * to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
  15. * copies of the Software, and to permit persons to whom the Software is
  16. * furnished to do so, subject to the following conditions:
  17. *
  18. * The above copyright notice and this permission notice shall be included in
  19. * all copies or substantial portions of the Software.
  20. *
  21. * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
  22. * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
  23. * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
  24. * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
  25. * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
  26. * OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
  27. * THE SOFTWARE.
  28. *
  29. * @package CodeIgniter
  30. * @author EllisLab Dev Team
  31. * @copyright Copyright (c) 2008 - 2014, EllisLab, Inc. (https://ellislab.com/)
  32. * @copyright Copyright (c) 2014 - 2019, British Columbia Institute of Technology (https://bcit.ca/)
  33. * @license https://opensource.org/licenses/MIT MIT License
  34. * @link https://codeigniter.com
  35. * @since Version 3.0.0
  36. * @filesource
  37. */
  38. defined('BASEPATH') OR exit('No direct script access allowed');
  39. /**
  40. * CodeIgniter Redis Caching Class
  41. *
  42. * @package CodeIgniter
  43. * @subpackage Libraries
  44. * @category Core
  45. * @author Anton Lindqvist <anton@qvister.se>
  46. * @link
  47. */
  48. class CI_Cache_redis extends CI_Driver
  49. {
  50. /**
  51. * Default config
  52. *
  53. * @static
  54. * @var array
  55. */
  56. protected static $_default_config = array(
  57. 'socket_type' => 'tcp',
  58. 'host' => '127.0.0.1',
  59. 'password' => NULL,
  60. 'port' => 6379,
  61. 'timeout' => 0
  62. );
  63. /**
  64. * Redis connection
  65. *
  66. * @var Redis
  67. */
  68. protected $_redis;
  69. /**
  70. * An internal cache for storing keys of serialized values.
  71. *
  72. * @var array
  73. */
  74. protected $_serialized = array();
  75. /**
  76. * del()/delete() method name depending on phpRedis version
  77. *
  78. * @var string
  79. */
  80. protected static $_delete_name;
  81. // ------------------------------------------------------------------------
  82. /**
  83. * Class constructor
  84. *
  85. * Setup Redis
  86. *
  87. * Loads Redis config file if present. Will halt execution
  88. * if a Redis connection can't be established.
  89. *
  90. * @return void
  91. * @see Redis::connect()
  92. */
  93. public function __construct()
  94. {
  95. if ( ! $this->is_supported())
  96. {
  97. log_message('error', 'Cache: Failed to create Redis object; extension not loaded?');
  98. return;
  99. }
  100. isset(static::$_delete_name) OR static::$_delete_name = version_compare(phpversion('phpredis'), '5', '>=')
  101. ? 'del'
  102. : 'delete';
  103. $CI =& get_instance();
  104. if ($CI->config->load('redis', TRUE, TRUE))
  105. {
  106. $config = array_merge(self::$_default_config, $CI->config->item('redis'));
  107. }
  108. else
  109. {
  110. $config = self::$_default_config;
  111. }
  112. $this->_redis = new Redis();
  113. try
  114. {
  115. if ($config['socket_type'] === 'unix')
  116. {
  117. $success = $this->_redis->connect($config['socket']);
  118. }
  119. else // tcp socket
  120. {
  121. $success = $this->_redis->connect($config['host'], $config['port'], $config['timeout']);
  122. }
  123. if ( ! $success)
  124. {
  125. log_message('error', 'Cache: Redis connection failed. Check your configuration.');
  126. }
  127. if (isset($config['password']) && ! $this->_redis->auth($config['password']))
  128. {
  129. log_message('error', 'Cache: Redis authentication failed.');
  130. }
  131. }
  132. catch (RedisException $e)
  133. {
  134. log_message('error', 'Cache: Redis connection refused ('.$e->getMessage().')');
  135. }
  136. }
  137. // ------------------------------------------------------------------------
  138. /**
  139. * Get cache
  140. *
  141. * @param string $key Cache ID
  142. * @return mixed
  143. */
  144. public function get($key)
  145. {
  146. $value = $this->_redis->get($key);
  147. if ($value !== FALSE && $this->_redis->sIsMember('_ci_redis_serialized', $key))
  148. {
  149. return unserialize($value);
  150. }
  151. return $value;
  152. }
  153. // ------------------------------------------------------------------------
  154. /**
  155. * Save cache
  156. *
  157. * @param string $id Cache ID
  158. * @param mixed $data Data to save
  159. * @param int $ttl Time to live in seconds
  160. * @param bool $raw Whether to store the raw value (unused)
  161. * @return bool TRUE on success, FALSE on failure
  162. */
  163. public function save($id, $data, $ttl = 60, $raw = FALSE)
  164. {
  165. if (is_array($data) OR is_object($data))
  166. {
  167. if ( ! $this->_redis->sIsMember('_ci_redis_serialized', $id) && ! $this->_redis->sAdd('_ci_redis_serialized', $id))
  168. {
  169. return FALSE;
  170. }
  171. isset($this->_serialized[$id]) OR $this->_serialized[$id] = TRUE;
  172. $data = serialize($data);
  173. }
  174. else
  175. {
  176. $this->_redis->sRemove('_ci_redis_serialized', $id);
  177. }
  178. return $this->_redis->set($id, $data, $ttl);
  179. }
  180. // ------------------------------------------------------------------------
  181. /**
  182. * Delete from cache
  183. *
  184. * @param string $key Cache key
  185. * @return bool
  186. */
  187. public function delete($key)
  188. {
  189. if ($this->_redis->{static::$_delete_name}($key) !== 1)
  190. {
  191. return FALSE;
  192. }
  193. $this->_redis->sRemove('_ci_redis_serialized', $key);
  194. return TRUE;
  195. }
  196. // ------------------------------------------------------------------------
  197. /**
  198. * Increment a raw value
  199. *
  200. * @param string $id Cache ID
  201. * @param int $offset Step/value to add
  202. * @return mixed New value on success or FALSE on failure
  203. */
  204. public function increment($id, $offset = 1)
  205. {
  206. return $this->_redis->incrBy($id, $offset);
  207. }
  208. // ------------------------------------------------------------------------
  209. /**
  210. * Decrement a raw value
  211. *
  212. * @param string $id Cache ID
  213. * @param int $offset Step/value to reduce by
  214. * @return mixed New value on success or FALSE on failure
  215. */
  216. public function decrement($id, $offset = 1)
  217. {
  218. return $this->_redis->decrBy($id, $offset);
  219. }
  220. // ------------------------------------------------------------------------
  221. /**
  222. * Clean cache
  223. *
  224. * @return bool
  225. * @see Redis::flushDB()
  226. */
  227. public function clean()
  228. {
  229. return $this->_redis->flushDB();
  230. }
  231. // ------------------------------------------------------------------------
  232. /**
  233. * Get cache driver info
  234. *
  235. * @param string $type Not supported in Redis.
  236. * Only included in order to offer a
  237. * consistent cache API.
  238. * @return array
  239. * @see Redis::info()
  240. */
  241. public function cache_info($type = NULL)
  242. {
  243. return $this->_redis->info();
  244. }
  245. // ------------------------------------------------------------------------
  246. /**
  247. * Get cache metadata
  248. *
  249. * @param string $key Cache key
  250. * @return array
  251. */
  252. public function get_metadata($key)
  253. {
  254. $value = $this->get($key);
  255. if ($value !== FALSE)
  256. {
  257. return array(
  258. 'expire' => time() + $this->_redis->ttl($key),
  259. 'data' => $value
  260. );
  261. }
  262. return FALSE;
  263. }
  264. // ------------------------------------------------------------------------
  265. /**
  266. * Check if Redis driver is supported
  267. *
  268. * @return bool
  269. */
  270. public function is_supported()
  271. {
  272. return extension_loaded('redis');
  273. }
  274. // ------------------------------------------------------------------------
  275. /**
  276. * Class destructor
  277. *
  278. * Closes the connection to Redis if present.
  279. *
  280. * @return void
  281. */
  282. public function __destruct()
  283. {
  284. if ($this->_redis)
  285. {
  286. $this->_redis->close();
  287. }
  288. }
  289. }