You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

372 lines
13KB

  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\caching;
  8. use Yii;
  9. use yii\base\InvalidConfigException;
  10. /**
  11. * MemCache implements a cache application component based on [memcache](http://pecl.php.net/package/memcache)
  12. * and [memcached](http://pecl.php.net/package/memcached).
  13. *
  14. * MemCache supports both [memcache](http://pecl.php.net/package/memcache) and
  15. * [memcached](http://pecl.php.net/package/memcached). By setting [[useMemcached]] to be true or false,
  16. * one can let MemCache to use either memcached or memcache, respectively.
  17. *
  18. * MemCache can be configured with a list of memcache servers by settings its [[servers]] property.
  19. * By default, MemCache assumes there is a memcache server running on localhost at port 11211.
  20. *
  21. * See [[Cache]] for common cache operations that MemCache supports.
  22. *
  23. * Note, there is no security measure to protected data in memcache.
  24. * All data in memcache can be accessed by any process running in the system.
  25. *
  26. * To use MemCache as the cache application component, configure the application as follows,
  27. *
  28. * ```php
  29. * [
  30. * 'components' => [
  31. * 'cache' => [
  32. * 'class' => 'yii\caching\MemCache',
  33. * 'servers' => [
  34. * [
  35. * 'host' => 'server1',
  36. * 'port' => 11211,
  37. * 'weight' => 60,
  38. * ],
  39. * [
  40. * 'host' => 'server2',
  41. * 'port' => 11211,
  42. * 'weight' => 40,
  43. * ],
  44. * ],
  45. * ],
  46. * ],
  47. * ]
  48. * ```
  49. *
  50. * In the above, two memcache servers are used: server1 and server2. You can configure more properties of
  51. * each server, such as `persistent`, `weight`, `timeout`. Please see [[MemCacheServer]] for available options.
  52. *
  53. * @property \Memcache|\Memcached $memcache The memcache (or memcached) object used by this cache component.
  54. * This property is read-only.
  55. * @property MemCacheServer[] $servers List of memcache server configurations. Note that the type of this
  56. * property differs in getter and setter. See [[getServers()]] and [[setServers()]] for details.
  57. *
  58. * @author Qiang Xue <qiang.xue@gmail.com>
  59. * @since 2.0
  60. */
  61. class MemCache extends Cache
  62. {
  63. /**
  64. * @var boolean whether to use memcached or memcache as the underlying caching extension.
  65. * If true, [memcached](http://pecl.php.net/package/memcached) will be used.
  66. * If false, [memcache](http://pecl.php.net/package/memcache) will be used.
  67. * Defaults to false.
  68. */
  69. public $useMemcached = false;
  70. /**
  71. * @var string an ID that identifies a Memcached instance. This property is used only when [[useMemcached]] is true.
  72. * By default the Memcached instances are destroyed at the end of the request. To create an instance that
  73. * persists between requests, you may specify a unique ID for the instance. All instances created with the
  74. * same ID will share the same connection.
  75. * @see http://ca2.php.net/manual/en/memcached.construct.php
  76. */
  77. public $persistentId;
  78. /**
  79. * @var array options for Memcached. This property is used only when [[useMemcached]] is true.
  80. * @see http://ca2.php.net/manual/en/memcached.setoptions.php
  81. */
  82. public $options;
  83. /**
  84. * @var string memcached sasl username. This property is used only when [[useMemcached]] is true.
  85. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  86. */
  87. public $username;
  88. /**
  89. * @var string memcached sasl password. This property is used only when [[useMemcached]] is true.
  90. * @see http://php.net/manual/en/memcached.setsaslauthdata.php
  91. */
  92. public $password;
  93. /**
  94. * @var \Memcache|\Memcached the Memcache instance
  95. */
  96. private $_cache;
  97. /**
  98. * @var array list of memcache server configurations
  99. */
  100. private $_servers = [];
  101. /**
  102. * Initializes this application component.
  103. * It creates the memcache instance and adds memcache servers.
  104. */
  105. public function init()
  106. {
  107. parent::init();
  108. $this->addServers($this->getMemcache(), $this->getServers());
  109. }
  110. /**
  111. * Add servers to the server pool of the cache specified
  112. *
  113. * @param \Memcache|\Memcached $cache
  114. * @param MemCacheServer[] $servers
  115. * @throws InvalidConfigException
  116. */
  117. protected function addServers($cache, $servers)
  118. {
  119. if (empty($servers)) {
  120. $servers = [new MemCacheServer([
  121. 'host' => '127.0.0.1',
  122. 'port' => 11211,
  123. ])];
  124. } else {
  125. foreach ($servers as $server) {
  126. if ($server->host === null) {
  127. throw new InvalidConfigException("The 'host' property must be specified for every memcache server.");
  128. }
  129. }
  130. }
  131. if ($this->useMemcached) {
  132. $this->addMemcachedServers($cache, $servers);
  133. } else {
  134. $this->addMemcacheServers($cache, $servers);
  135. }
  136. }
  137. /**
  138. * Add servers to the server pool of the cache specified
  139. * Used for memcached PECL extension.
  140. *
  141. * @param \Memcached $cache
  142. * @param MemCacheServer[] $servers
  143. */
  144. protected function addMemcachedServers($cache, $servers)
  145. {
  146. $existingServers = [];
  147. if ($this->persistentId !== null) {
  148. foreach ($cache->getServerList() as $s) {
  149. $existingServers[$s['host'] . ':' . $s['port']] = true;
  150. }
  151. }
  152. foreach ($servers as $server) {
  153. if (empty($existingServers) || !isset($existingServers[$server->host . ':' . $server->port])) {
  154. $cache->addServer($server->host, $server->port, $server->weight);
  155. }
  156. }
  157. }
  158. /**
  159. * Add servers to the server pool of the cache specified
  160. * Used for memcache PECL extension.
  161. *
  162. * @param \Memcache $cache
  163. * @param MemCacheServer[] $servers
  164. */
  165. protected function addMemcacheServers($cache, $servers)
  166. {
  167. $class = new \ReflectionClass($cache);
  168. $paramCount = $class->getMethod('addServer')->getNumberOfParameters();
  169. foreach ($servers as $server) {
  170. // $timeout is used for memcache versions that do not have $timeoutms parameter
  171. $timeout = (int) ($server->timeout / 1000) + (($server->timeout % 1000 > 0) ? 1 : 0);
  172. if ($paramCount === 9) {
  173. $cache->addserver(
  174. $server->host,
  175. $server->port,
  176. $server->persistent,
  177. $server->weight,
  178. $timeout,
  179. $server->retryInterval,
  180. $server->status,
  181. $server->failureCallback,
  182. $server->timeout
  183. );
  184. } else {
  185. $cache->addserver(
  186. $server->host,
  187. $server->port,
  188. $server->persistent,
  189. $server->weight,
  190. $timeout,
  191. $server->retryInterval,
  192. $server->status,
  193. $server->failureCallback
  194. );
  195. }
  196. }
  197. }
  198. /**
  199. * Returns the underlying memcache (or memcached) object.
  200. * @return \Memcache|\Memcached the memcache (or memcached) object used by this cache component.
  201. * @throws InvalidConfigException if memcache or memcached extension is not loaded
  202. */
  203. public function getMemcache()
  204. {
  205. if ($this->_cache === null) {
  206. $extension = $this->useMemcached ? 'memcached' : 'memcache';
  207. if (!extension_loaded($extension)) {
  208. throw new InvalidConfigException("MemCache requires PHP $extension extension to be loaded.");
  209. }
  210. if ($this->useMemcached) {
  211. $this->_cache = $this->persistentId !== null ? new \Memcached($this->persistentId) : new \Memcached;
  212. if ($this->username !== null || $this->password !== null) {
  213. $this->_cache->setOption(\Memcached::OPT_BINARY_PROTOCOL, true);
  214. $this->_cache->setSaslAuthData($this->username, $this->password);
  215. }
  216. if (!empty($this->options)) {
  217. $this->_cache->setOptions($this->options);
  218. }
  219. } else {
  220. $this->_cache = new \Memcache;
  221. }
  222. }
  223. return $this->_cache;
  224. }
  225. /**
  226. * Returns the memcache or memcached server configurations.
  227. * @return MemCacheServer[] list of memcache server configurations.
  228. */
  229. public function getServers()
  230. {
  231. return $this->_servers;
  232. }
  233. /**
  234. * @param array $config list of memcache or memcached server configurations. Each element must be an array
  235. * with the following keys: host, port, persistent, weight, timeout, retryInterval, status.
  236. * @see http://php.net/manual/en/memcache.addserver.php
  237. * @see http://php.net/manual/en/memcached.addserver.php
  238. */
  239. public function setServers($config)
  240. {
  241. foreach ($config as $c) {
  242. $this->_servers[] = new MemCacheServer($c);
  243. }
  244. }
  245. /**
  246. * Retrieves a value from cache with a specified key.
  247. * This is the implementation of the method declared in the parent class.
  248. * @param string $key a unique key identifying the cached value
  249. * @return string|boolean the value stored in cache, false if the value is not in the cache or expired.
  250. */
  251. protected function getValue($key)
  252. {
  253. return $this->_cache->get($key);
  254. }
  255. /**
  256. * Retrieves multiple values from cache with the specified keys.
  257. * @param array $keys a list of keys identifying the cached values
  258. * @return array a list of cached values indexed by the keys
  259. */
  260. protected function getValues($keys)
  261. {
  262. return $this->useMemcached ? $this->_cache->getMulti($keys) : $this->_cache->get($keys);
  263. }
  264. /**
  265. * Stores a value identified by a key in cache.
  266. * This is the implementation of the method declared in the parent class.
  267. *
  268. * @param string $key the key identifying the value to be cached
  269. * @param string $value the value to be cached
  270. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  271. * @return boolean true if the value is successfully stored into cache, false otherwise
  272. */
  273. protected function setValue($key, $value, $duration)
  274. {
  275. $duration = $this->trimDuration($duration);
  276. $expire = $duration > 0 ? $duration + time() : 0;
  277. return $this->useMemcached ? $this->_cache->set($key, $value, $expire) : $this->_cache->set($key, $value, 0, $expire);
  278. }
  279. /**
  280. * Stores multiple key-value pairs in cache.
  281. * @param array $data array where key corresponds to cache key while value is the value stored
  282. * @param integer $duration the number of seconds in which the cached values will expire. 0 means never expire.
  283. * @return array array of failed keys. Always empty in case of using memcached.
  284. */
  285. protected function setValues($data, $duration)
  286. {
  287. $duration = $this->trimDuration($duration);
  288. if ($this->useMemcached) {
  289. $this->_cache->setMulti($data, $duration > 0 ? $duration + time() : 0);
  290. return [];
  291. } else {
  292. return parent::setValues($data, $duration);
  293. }
  294. }
  295. /**
  296. * Stores a value identified by a key into cache if the cache does not contain this key.
  297. * This is the implementation of the method declared in the parent class.
  298. *
  299. * @param string $key the key identifying the value to be cached
  300. * @param string $value the value to be cached
  301. * @param integer $duration the number of seconds in which the cached value will expire. 0 means never expire.
  302. * @return boolean true if the value is successfully stored into cache, false otherwise
  303. */
  304. protected function addValue($key, $value, $duration)
  305. {
  306. $duration = $this->trimDuration($duration);
  307. $expire = $duration > 0 ? $duration + time() : 0;
  308. return $this->useMemcached ? $this->_cache->add($key, $value, $expire) : $this->_cache->add($key, $value, 0, $expire);
  309. }
  310. /**
  311. * Deletes a value with the specified key from cache
  312. * This is the implementation of the method declared in the parent class.
  313. * @param string $key the key of the value to be deleted
  314. * @return boolean if no error happens during deletion
  315. */
  316. protected function deleteValue($key)
  317. {
  318. return $this->_cache->delete($key, 0);
  319. }
  320. /**
  321. * Deletes all values from cache.
  322. * This is the implementation of the method declared in the parent class.
  323. * @return boolean whether the flush operation was successful.
  324. */
  325. protected function flushValues()
  326. {
  327. return $this->_cache->flush();
  328. }
  329. /**
  330. * Trims duration to 30 days (2592000 seconds).
  331. * @param integer $duration the number of seconds
  332. * @return integer the duration
  333. * @since 2.0.7
  334. * @see http://php.net/manual/en/memcache.set.php
  335. * @see http://php.net/manual/en/memcached.expiration.php
  336. */
  337. protected function trimDuration($duration)
  338. {
  339. if ($duration > 2592000) {
  340. Yii::warning('Duration has been truncated to 30 days due to Memcache/Memcached limitation.', __METHOD__);
  341. return 2592000;
  342. }
  343. return $duration;
  344. }
  345. }