Cache.php 8.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278
  1. <?php
  2. /**
  3. * @link http://www.yiiframework.com/
  4. * @copyright Copyright (c) 2008 Yii Software LLC
  5. * @license http://www.yiiframework.com/license/
  6. */
  7. namespace yii\redis;
  8. use Yii;
  9. use yii\di\Instance;
  10. /**
  11. * Redis Cache implements a cache application component based on [redis](http://redis.io/) key-value store.
  12. *
  13. * Redis Cache requires redis version 2.6.12 or higher to work properly.
  14. *
  15. * It needs to be configured with a redis [[Connection]] that is also configured as an application component.
  16. * By default it will use the `redis` application component.
  17. *
  18. * See [[Cache]] manual for common cache operations that redis Cache supports.
  19. *
  20. * Unlike the [[Cache]], redis Cache allows the expire parameter of [[set]], [[add]], [[mset]] and [[madd]] to
  21. * be a floating point number, so you may specify the time in milliseconds (e.g. 0.1 will be 100 milliseconds).
  22. *
  23. * To use redis Cache as the cache application component, configure the application as follows,
  24. *
  25. * ~~~
  26. * [
  27. * 'components' => [
  28. * 'cache' => [
  29. * 'class' => 'yii\redis\Cache',
  30. * 'redis' => [
  31. * 'hostname' => 'localhost',
  32. * 'port' => 6379,
  33. * 'database' => 0,
  34. * ]
  35. * ],
  36. * ],
  37. * ]
  38. * ~~~
  39. *
  40. * Or if you have configured the redis [[Connection]] as an application component, the following is sufficient:
  41. *
  42. * ~~~
  43. * [
  44. * 'components' => [
  45. * 'cache' => [
  46. * 'class' => 'yii\redis\Cache',
  47. * // 'redis' => 'redis' // id of the connection application component
  48. * ],
  49. * ],
  50. * ]
  51. * ~~~
  52. *
  53. * If you have multiple redis replicas (e.g. AWS ElasticCache Redis) you can configure the cache to
  54. * send read operations to the replicas. If no replicas are configured, all operations will be performed on the
  55. * master connection configured via the [[redis]] property.
  56. *
  57. * ~~~
  58. * [
  59. * 'components' => [
  60. * 'cache' => [
  61. * 'class' => 'yii\redis\Cache',
  62. * 'enableReplicas' => true,
  63. * 'replicas' => [
  64. * // config for replica redis connections, (default class will be yii\redis\Connection if not provided)
  65. * // you can optionally put in master as hostname as well, as all GET operation will use replicas
  66. * 'redis',//id of Redis [[Connection]] Component
  67. * ['hostname' => 'redis-slave-002.xyz.0001.apse1.cache.amazonaws.com'],
  68. * ['hostname' => 'redis-slave-003.xyz.0001.apse1.cache.amazonaws.com'],
  69. * ],
  70. * ],
  71. * ],
  72. * ]
  73. * ~~~
  74. *
  75. * @author Carsten Brandt <mail@cebe.cc>
  76. * @since 2.0
  77. */
  78. class Cache extends \yii\caching\Cache
  79. {
  80. /**
  81. * @var Connection|string|array the Redis [[Connection]] object or the application component ID of the Redis [[Connection]].
  82. * This can also be an array that is used to create a redis [[Connection]] instance in case you do not want do configure
  83. * redis connection as an application component.
  84. * After the Cache object is created, if you want to change this property, you should only assign it
  85. * with a Redis [[Connection]] object.
  86. */
  87. public $redis = 'redis';
  88. /**
  89. * @var bool whether to enable read / get from redis replicas.
  90. * @since 2.0.8
  91. * @see $replicas
  92. */
  93. public $enableReplicas = false;
  94. /**
  95. * @var array the Redis [[Connection]] configurations for redis replicas.
  96. * Each entry is a class configuration, which will be used to instantiate a replica connection.
  97. * The default class is [[Connection|yii\redis\Connection]]. You should at least provide a hostname.
  98. *
  99. * Configuration example:
  100. *
  101. * ```php
  102. * 'replicas' => [
  103. * 'redis',
  104. * ['hostname' => 'redis-slave-002.xyz.0001.apse1.cache.amazonaws.com'],
  105. * ['hostname' => 'redis-slave-003.xyz.0001.apse1.cache.amazonaws.com'],
  106. * ],
  107. * ```
  108. *
  109. * @since 2.0.8
  110. * @see $enableReplicas
  111. */
  112. public $replicas = [];
  113. /**
  114. * @var Connection currently active connection.
  115. */
  116. private $_replica;
  117. /**
  118. * Initializes the redis Cache component.
  119. * This method will initialize the [[redis]] property to make sure it refers to a valid redis connection.
  120. * @throws \yii\base\InvalidConfigException if [[redis]] is invalid.
  121. */
  122. public function init()
  123. {
  124. parent::init();
  125. $this->redis = Instance::ensure($this->redis, Connection::className());
  126. }
  127. /**
  128. * Checks whether a specified key exists in the cache.
  129. * This can be faster than getting the value from the cache if the data is big.
  130. * Note that this method does not check whether the dependency associated
  131. * with the cached data, if there is any, has changed. So a call to [[get]]
  132. * may return false while exists returns true.
  133. * @param mixed $key a key identifying the cached value. This can be a simple string or
  134. * a complex data structure consisting of factors representing the key.
  135. * @return bool true if a value exists in cache, false if the value is not in the cache or expired.
  136. */
  137. public function exists($key)
  138. {
  139. return (bool) $this->redis->executeCommand('EXISTS', [$this->buildKey($key)]);
  140. }
  141. /**
  142. * @inheritdoc
  143. */
  144. protected function getValue($key)
  145. {
  146. return $this->getReplica()->executeCommand('GET', [$key]);
  147. }
  148. /**
  149. * @inheritdoc
  150. */
  151. protected function getValues($keys)
  152. {
  153. $response = $this->getReplica()->executeCommand('MGET', $keys);
  154. $result = [];
  155. $i = 0;
  156. foreach ($keys as $key) {
  157. $result[$key] = $response[$i++];
  158. }
  159. return $result;
  160. }
  161. /**
  162. * @inheritdoc
  163. */
  164. protected function setValue($key, $value, $expire)
  165. {
  166. if ($expire == 0) {
  167. return (bool) $this->redis->executeCommand('SET', [$key, $value]);
  168. } else {
  169. $expire = (int) ($expire * 1000);
  170. return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire]);
  171. }
  172. }
  173. /**
  174. * @inheritdoc
  175. */
  176. protected function setValues($data, $expire)
  177. {
  178. $args = [];
  179. foreach ($data as $key => $value) {
  180. $args[] = $key;
  181. $args[] = $value;
  182. }
  183. $failedKeys = [];
  184. if ($expire == 0) {
  185. $this->redis->executeCommand('MSET', $args);
  186. } else {
  187. $expire = (int) ($expire * 1000);
  188. $this->redis->executeCommand('MULTI');
  189. $this->redis->executeCommand('MSET', $args);
  190. $index = [];
  191. foreach ($data as $key => $value) {
  192. $this->redis->executeCommand('PEXPIRE', [$key, $expire]);
  193. $index[] = $key;
  194. }
  195. $result = $this->redis->executeCommand('EXEC');
  196. array_shift($result);
  197. foreach ($result as $i => $r) {
  198. if ($r != 1) {
  199. $failedKeys[] = $index[$i];
  200. }
  201. }
  202. }
  203. return $failedKeys;
  204. }
  205. /**
  206. * @inheritdoc
  207. */
  208. protected function addValue($key, $value, $expire)
  209. {
  210. if ($expire == 0) {
  211. return (bool) $this->redis->executeCommand('SET', [$key, $value, 'NX']);
  212. } else {
  213. $expire = (int) ($expire * 1000);
  214. return (bool) $this->redis->executeCommand('SET', [$key, $value, 'PX', $expire, 'NX']);
  215. }
  216. }
  217. /**
  218. * @inheritdoc
  219. */
  220. protected function deleteValue($key)
  221. {
  222. return (bool) $this->redis->executeCommand('DEL', [$key]);
  223. }
  224. /**
  225. * @inheritdoc
  226. */
  227. protected function flushValues()
  228. {
  229. return $this->redis->executeCommand('FLUSHDB');
  230. }
  231. /**
  232. * It will return the current Replica Redis [[Connection]], and fall back to default [[redis]] [[Connection]]
  233. * defined in this instance. Only used in getValue() and getValues().
  234. * @since 2.0.8
  235. * @return array|string|Connection
  236. * @throws \yii\base\InvalidConfigException
  237. */
  238. protected function getReplica()
  239. {
  240. if ($this->enableReplicas === false) {
  241. return $this->redis;
  242. }
  243. if ($this->_replica !== null) {
  244. return $this->_replica;
  245. }
  246. if (empty($this->replicas)) {
  247. return $this->_replica = $this->redis;
  248. }
  249. $replicas = $this->replicas;
  250. shuffle($replicas);
  251. $config = array_shift($replicas);
  252. $this->_replica = Instance::ensure($config, Connection::className());
  253. return $this->_replica;
  254. }
  255. }