MemcachedEngine.php 8.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288
  1. <?php
  2. /**
  3. * CakePHP(tm) : Rapid Development Framework (http://cakephp.org)
  4. * Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  5. *
  6. * Licensed under The MIT License
  7. * For full copyright and license information, please see the LICENSE.txt
  8. * Redistributions of files must retain the above copyright notice.
  9. *
  10. * @copyright Copyright (c) Cake Software Foundation, Inc. (http://cakefoundation.org)
  11. * @link http://cakephp.org CakePHP(tm) Project
  12. * @since CakePHP(tm) v 2.5.0
  13. * @license http://www.opensource.org/licenses/mit-license.php MIT License
  14. */
  15. /**
  16. * Memcached storage engine for cache. Memcached has some limitations in the amount of
  17. * control you have over expire times far in the future. See MemcachedEngine::write() for
  18. * more information.
  19. *
  20. * Main advantage of this Memcached engine over the memcached engine is
  21. * support of binary protocol, and igbibnary serialization
  22. * (if memcached extension compiled with --enable-igbinary)
  23. * Compressed keys can also be incremented/decremented
  24. *
  25. * @package Cake.Cache.Engine
  26. */
  27. class MemcachedEngine extends CacheEngine {
  28. /**
  29. * memcached wrapper.
  30. *
  31. * @var Memcache
  32. */
  33. protected $_Memcached = null;
  34. /**
  35. * Settings
  36. *
  37. * - servers = string or array of memcached servers, default => 127.0.0.1. If an
  38. * array MemcacheEngine will use them as a pool.
  39. * - compress = boolean, default => false
  40. * - persistent = string The name of the persistent connection. All configurations using
  41. * the same persistent value will share a single underlying connection.
  42. *
  43. * @var array
  44. */
  45. public $settings = array();
  46. /**
  47. * Initialize the Cache Engine
  48. *
  49. * Called automatically by the cache frontend
  50. * To reinitialize the settings call Cache::engine('EngineName', [optional] settings = array());
  51. *
  52. * @param array $settings array of setting for the engine
  53. * @return boolean True if the engine has been successfully initialized, false if not
  54. * @throws CacheException when you try use authentication without Memcached compiled with SASL support
  55. */
  56. public function init($settings = array()) {
  57. if (!class_exists('Memcached')) {
  58. return false;
  59. }
  60. if (!isset($settings['prefix'])) {
  61. $settings['prefix'] = Inflector::slug(APP_DIR) . '_';
  62. }
  63. $settings += array(
  64. 'engine' => 'Memcached',
  65. 'servers' => array('127.0.0.1'),
  66. 'compress' => false,
  67. 'persistent' => false,
  68. 'login' => null,
  69. 'password' => null,
  70. );
  71. parent::init($settings);
  72. if (!is_array($this->settings['servers'])) {
  73. $this->settings['servers'] = array($this->settings['servers']);
  74. }
  75. if (isset($this->_Memcached)) {
  76. return true;
  77. }
  78. $this->_Memcached = new Memcached($this->settings['persistent'] ? (string)$this->settings['persistent'] : null);
  79. $this->_setOptions();
  80. if (count($this->_Memcached->getServerList())) {
  81. return true;
  82. }
  83. $servers = array();
  84. foreach ($this->settings['servers'] as $server) {
  85. $servers[] = $this->_parseServerString($server);
  86. }
  87. if (!$this->_Memcached->addServers($servers)) {
  88. return false;
  89. }
  90. if ($this->settings['login'] !== null && $this->settings['password'] !== null) {
  91. if (!method_exists($this->_Memcached, 'setSaslAuthData')) {
  92. throw new CacheException(
  93. __d('cake_dev', 'Memcached extension is not build with SASL support')
  94. );
  95. }
  96. $this->_Memcached->setSaslAuthData($this->settings['login'], $this->settings['password']);
  97. }
  98. return true;
  99. }
  100. /**
  101. * Settings the memcached instance
  102. *
  103. */
  104. protected function _setOptions() {
  105. $this->_Memcached->setOption(Memcached::OPT_LIBKETAMA_COMPATIBLE, true);
  106. if (Memcached::HAVE_IGBINARY) {
  107. $this->_Memcached->setOption(Memcached::OPT_SERIALIZER, Memcached::SERIALIZER_IGBINARY);
  108. }
  109. // Check for Amazon ElastiCache instance
  110. if (defined('Memcached::OPT_CLIENT_MODE') && defined('Memcached::DYNAMIC_CLIENT_MODE')) {
  111. $this->_Memcached->setOption(Memcached::OPT_CLIENT_MODE, Memcached::DYNAMIC_CLIENT_MODE);
  112. }
  113. $this->_Memcached->setOption(Memcached::OPT_COMPRESSION, (bool)$this->settings['compress']);
  114. }
  115. /**
  116. * Parses the server address into the host/port. Handles both IPv6 and IPv4
  117. * addresses and Unix sockets
  118. *
  119. * @param string $server The server address string.
  120. * @return array Array containing host, port
  121. */
  122. protected function _parseServerString($server) {
  123. if ($server[0] === 'u') {
  124. return array($server, 0);
  125. }
  126. if (substr($server, 0, 1) === '[') {
  127. $position = strpos($server, ']:');
  128. if ($position !== false) {
  129. $position++;
  130. }
  131. } else {
  132. $position = strpos($server, ':');
  133. }
  134. $port = 11211;
  135. $host = $server;
  136. if ($position !== false) {
  137. $host = substr($server, 0, $position);
  138. $port = substr($server, $position + 1);
  139. }
  140. return array($host, (int)$port);
  141. }
  142. /**
  143. * Write data for key into cache. When using memcached as your cache engine
  144. * remember that the Memcached pecl extension does not support cache expiry times greater
  145. * than 30 days in the future. Any duration greater than 30 days will be treated as never expiring.
  146. *
  147. * @param string $key Identifier for the data
  148. * @param mixed $value Data to be cached
  149. * @param integer $duration How long to cache the data, in seconds
  150. * @return boolean True if the data was successfully cached, false on failure
  151. * @see http://php.net/manual/en/memcache.set.php
  152. */
  153. public function write($key, $value, $duration) {
  154. if ($duration > 30 * DAY) {
  155. $duration = 0;
  156. }
  157. return $this->_Memcached->set($key, $value, $duration);
  158. }
  159. /**
  160. * Read a key from the cache
  161. *
  162. * @param string $key Identifier for the data
  163. * @return mixed The cached data, or false if the data doesn't exist, has expired, or if there was an error fetching it
  164. */
  165. public function read($key) {
  166. return $this->_Memcached->get($key);
  167. }
  168. /**
  169. * Increments the value of an integer cached key
  170. *
  171. * @param string $key Identifier for the data
  172. * @param integer $offset How much to increment
  173. * @return New incremented value, false otherwise
  174. * @throws CacheException when you try to increment with compress = true
  175. */
  176. public function increment($key, $offset = 1) {
  177. return $this->_Memcached->increment($key, $offset);
  178. }
  179. /**
  180. * Decrements the value of an integer cached key
  181. *
  182. * @param string $key Identifier for the data
  183. * @param integer $offset How much to subtract
  184. * @return New decremented value, false otherwise
  185. * @throws CacheException when you try to decrement with compress = true
  186. */
  187. public function decrement($key, $offset = 1) {
  188. return $this->_Memcached->decrement($key, $offset);
  189. }
  190. /**
  191. * Delete a key from the cache
  192. *
  193. * @param string $key Identifier for the data
  194. * @return boolean True if the value was successfully deleted, false if it didn't exist or couldn't be removed
  195. */
  196. public function delete($key) {
  197. return $this->_Memcached->delete($key);
  198. }
  199. /**
  200. * Delete all keys from the cache
  201. *
  202. * @param boolean $check
  203. * @return boolean True if the cache was successfully cleared, false otherwise
  204. */
  205. public function clear($check) {
  206. if ($check) {
  207. return true;
  208. }
  209. $keys = $this->_Memcached->getAllKeys();
  210. foreach ($keys as $key) {
  211. if (strpos($key, $this->settings['prefix']) === 0) {
  212. $this->_Memcached->delete($key);
  213. }
  214. }
  215. return true;
  216. }
  217. /**
  218. * Returns the `group value` for each of the configured groups
  219. * If the group initial value was not found, then it initializes
  220. * the group accordingly.
  221. *
  222. * @return array
  223. */
  224. public function groups() {
  225. if (empty($this->_compiledGroupNames)) {
  226. foreach ($this->settings['groups'] as $group) {
  227. $this->_compiledGroupNames[] = $this->settings['prefix'] . $group;
  228. }
  229. }
  230. $groups = $this->_Memcached->getMulti($this->_compiledGroupNames);
  231. if (count($groups) !== count($this->settings['groups'])) {
  232. foreach ($this->_compiledGroupNames as $group) {
  233. if (!isset($groups[$group])) {
  234. $this->_Memcached->set($group, 1, 0);
  235. $groups[$group] = 1;
  236. }
  237. }
  238. ksort($groups);
  239. }
  240. $result = array();
  241. $groups = array_values($groups);
  242. foreach ($this->settings['groups'] as $i => $group) {
  243. $result[] = $group . $groups[$i];
  244. }
  245. return $result;
  246. }
  247. /**
  248. * Increments the group value to simulate deletion of all keys under a group
  249. * old values will remain in storage until they expire.
  250. *
  251. * @return boolean success
  252. */
  253. public function clearGroup($group) {
  254. return (bool)$this->_Memcached->increment($this->settings['prefix'] . $group);
  255. }
  256. }