Memcache.php 12 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354
  1. <?php
  2. /**
  3. * [Kohana Cache](api/Kohana_Cache) Memcache driver,
  4. *
  5. * ### Supported cache engines
  6. *
  7. * * [Memcache](http://www.php.net/manual/en/book.memcache.php)
  8. * * [Memcached-tags](http://code.google.com/p/memcached-tags/)
  9. *
  10. * ### Configuration example
  11. *
  12. * Below is an example of a _memcache_ server configuration.
  13. *
  14. * return array(
  15. * 'default' => array( // Default group
  16. * 'driver' => 'memcache', // using Memcache driver
  17. * 'servers' => array( // Available server definitions
  18. * // First memcache server server
  19. * array(
  20. * 'host' => 'localhost',
  21. * 'port' => 11211,
  22. * 'persistent' => FALSE
  23. * 'weight' => 1,
  24. * 'timeout' => 1,
  25. * 'retry_interval' => 15,
  26. * 'status' => TRUE,
  27. * 'instant_death' => TRUE,
  28. * 'failure_callback' => array('className', 'classMethod')
  29. * ),
  30. * // Second memcache server
  31. * array(
  32. * 'host' => '192.168.1.5',
  33. * 'port' => 22122,
  34. * 'persistent' => TRUE
  35. * )
  36. * ),
  37. * 'compression' => FALSE, // Use compression?
  38. * ),
  39. * )
  40. *
  41. * In cases where only one cache group is required, if the group is named `default` there is
  42. * no need to pass the group name when instantiating a cache instance.
  43. *
  44. * #### General cache group configuration settings
  45. *
  46. * Below are the settings available to all types of cache driver.
  47. *
  48. * Name | Required | Description
  49. * -------------- | -------- | ---------------------------------------------------------------
  50. * driver | __YES__ | (_string_) The driver type to use
  51. * servers | __YES__ | (_array_) Associative array of server details, must include a __host__ key. (see _Memcache server configuration_ below)
  52. * compression | __NO__ | (_boolean_) Use data compression when caching
  53. *
  54. * #### Memcache server configuration
  55. *
  56. * The following settings should be used when defining each memcache server
  57. *
  58. * Name | Required | Description
  59. * ---------------- | -------- | ---------------------------------------------------------------
  60. * host | __YES__ | (_string_) The host of the memcache server, i.e. __localhost__; or __127.0.0.1__; or __memcache.domain.tld__
  61. * port | __NO__ | (_integer_) Point to the port where memcached is listening for connections. Set this parameter to 0 when using UNIX domain sockets. Default __11211__
  62. * persistent | __NO__ | (_boolean_) Controls the use of a persistent connection. Default __TRUE__
  63. * weight | __NO__ | (_integer_) Number of buckets to create for this server which in turn control its probability of it being selected. The probability is relative to the total weight of all servers. Default __1__
  64. * timeout | __NO__ | (_integer_) Value in seconds which will be used for connecting to the daemon. Think twice before changing the default value of 1 second - you can lose all the advantages of caching if your connection is too slow. Default __1__
  65. * retry_interval | __NO__ | (_integer_) Controls how often a failed server will be retried, the default value is 15 seconds. Setting this parameter to -1 disables automatic retry. Default __15__
  66. * status | __NO__ | (_boolean_) Controls if the server should be flagged as online. Default __TRUE__
  67. * failure_callback | __NO__ | (_[callback](http://www.php.net/manual/en/language.pseudo-types.php#language.types.callback)_) Allows the user to specify a callback function to run upon encountering an error. The callback is run before failover is attempted. The function takes two parameters, the hostname and port of the failed server. Default __NULL__
  68. *
  69. * ### System requirements
  70. *
  71. * * Kohana 3.0.x
  72. * * PHP 5.2.4 or greater
  73. * * Memcache (plus Memcached-tags for native tagging support)
  74. * * Zlib
  75. *
  76. * @package Kohana/Cache
  77. * @category Base
  78. * @version 2.0
  79. * @author Kohana Team
  80. * @copyright (c) Kohana Team
  81. * @license https://koseven.ga/LICENSE.md
  82. */
  83. class Kohana_Cache_Memcache extends Cache implements Cache_Arithmetic {
  84. // Memcache has a maximum cache lifetime of 30 days
  85. const CACHE_CEILING = 2592000;
  86. /**
  87. * Memcache resource
  88. *
  89. * @var Memcache
  90. */
  91. protected $_memcache;
  92. /**
  93. * Flags to use when storing values
  94. *
  95. * @var string
  96. */
  97. protected $_flags;
  98. /**
  99. * The default configuration for the memcached server
  100. *
  101. * @var array
  102. */
  103. protected $_default_config = [];
  104. /**
  105. * Constructs the memcache Kohana_Cache object
  106. *
  107. * @param array $config configuration
  108. * @throws Cache_Exception
  109. */
  110. protected function __construct(array $config)
  111. {
  112. // Check for the memcache extention
  113. if ( ! extension_loaded('memcache'))
  114. {
  115. throw new Cache_Exception('Memcache PHP extention not loaded');
  116. }
  117. parent::__construct($config);
  118. // Setup Memcache
  119. $this->_memcache = new Memcache;
  120. // Load servers from configuration
  121. $servers = Arr::get($this->_config, 'servers', NULL);
  122. if ( ! $servers)
  123. {
  124. // Throw an exception if no server found
  125. throw new Cache_Exception('No Memcache servers defined in configuration');
  126. }
  127. // Setup default server configuration
  128. $this->_default_config = [
  129. 'host' => 'localhost',
  130. 'port' => 11211,
  131. 'persistent' => FALSE,
  132. 'weight' => 1,
  133. 'timeout' => 1,
  134. 'retry_interval' => 15,
  135. 'status' => TRUE,
  136. 'instant_death' => TRUE,
  137. 'failure_callback' => [$this, '_failed_request'],
  138. ];
  139. // Add the memcache servers to the pool
  140. foreach ($servers as $server)
  141. {
  142. // Merge the defined config with defaults
  143. $server += $this->_default_config;
  144. if ( ! $this->_memcache->addServer($server['host'], $server['port'], $server['persistent'], $server['weight'], $server['timeout'], $server['retry_interval'], $server['status'], $server['failure_callback']))
  145. {
  146. throw new Cache_Exception('Memcache could not connect to host \':host\' using port \':port\'', [':host' => $server['host'], ':port' => $server['port']]);
  147. }
  148. }
  149. // Setup the flags
  150. $this->_flags = Arr::get($this->_config, 'compression', FALSE) ? MEMCACHE_COMPRESSED : FALSE;
  151. }
  152. /**
  153. * Retrieve a cached value entry by id.
  154. *
  155. * // Retrieve cache entry from memcache group
  156. * $data = Cache::instance('memcache')->get('foo');
  157. *
  158. * // Retrieve cache entry from memcache group and return 'bar' if miss
  159. * $data = Cache::instance('memcache')->get('foo', 'bar');
  160. *
  161. * @param string $id id of cache to entry
  162. * @param string $default default value to return if cache miss
  163. * @return mixed
  164. * @throws Cache_Exception
  165. */
  166. public function get($id, $default = NULL)
  167. {
  168. // Get the value from Memcache
  169. $value = $this->_memcache->get($this->_sanitize_id($id));
  170. // If the value wasn't found, normalise it
  171. if ($value === FALSE)
  172. {
  173. $value = (NULL === $default) ? NULL : $default;
  174. }
  175. // Return the value
  176. return $value;
  177. }
  178. /**
  179. * Set a value to cache with id and lifetime
  180. *
  181. * $data = 'bar';
  182. *
  183. * // Set 'bar' to 'foo' in memcache group for 10 minutes
  184. * if (Cache::instance('memcache')->set('foo', $data, 600))
  185. * {
  186. * // Cache was set successfully
  187. * return
  188. * }
  189. *
  190. * @param string $id id of cache entry
  191. * @param mixed $data data to set to cache
  192. * @param integer $lifetime lifetime in seconds, maximum value 2592000
  193. * @return boolean
  194. */
  195. public function set($id, $data, $lifetime = 3600)
  196. {
  197. // If the lifetime is greater than the ceiling
  198. if ($lifetime > Cache_Memcache::CACHE_CEILING)
  199. {
  200. // Set the lifetime to maximum cache time
  201. $lifetime = Cache_Memcache::CACHE_CEILING + time();
  202. }
  203. // Else if the lifetime is greater than zero
  204. elseif ($lifetime > 0)
  205. {
  206. $lifetime += time();
  207. }
  208. // Else
  209. else
  210. {
  211. // Normalise the lifetime
  212. $lifetime = 0;
  213. }
  214. // Set the data to memcache
  215. return $this->_memcache->set($this->_sanitize_id($id), $data, $this->_flags, $lifetime);
  216. }
  217. /**
  218. * Delete a cache entry based on id
  219. *
  220. * // Delete the 'foo' cache entry immediately
  221. * Cache::instance('memcache')->delete('foo');
  222. *
  223. * // Delete the 'bar' cache entry after 30 seconds
  224. * Cache::instance('memcache')->delete('bar', 30);
  225. *
  226. * @param string $id id of entry to delete
  227. * @param integer $timeout timeout of entry, if zero item is deleted immediately, otherwise the item will delete after the specified value in seconds
  228. * @return boolean
  229. */
  230. public function delete($id, $timeout = 0)
  231. {
  232. // Delete the id
  233. return $this->_memcache->delete($this->_sanitize_id($id), $timeout);
  234. }
  235. /**
  236. * Delete all cache entries.
  237. *
  238. * Beware of using this method when
  239. * using shared memory cache systems, as it will wipe every
  240. * entry within the system for all clients.
  241. *
  242. * // Delete all cache entries in the default group
  243. * Cache::instance('memcache')->delete_all();
  244. *
  245. * @return boolean
  246. */
  247. public function delete_all()
  248. {
  249. $result = $this->_memcache->flush();
  250. // We must sleep after flushing, or overwriting will not work!
  251. // @see http://php.net/manual/en/function.memcache-flush.php#81420
  252. sleep(1);
  253. return $result;
  254. }
  255. /**
  256. * Callback method for Memcache::failure_callback to use if any Memcache call
  257. * on a particular server fails. This method switches off that instance of the
  258. * server if the configuration setting `instant_death` is set to `TRUE`.
  259. *
  260. * @param string $hostname
  261. * @param integer $port
  262. * @return void|boolean
  263. * @since 3.0.8
  264. */
  265. public function _failed_request($hostname, $port)
  266. {
  267. if ( ! $this->_config['instant_death'])
  268. return;
  269. // Setup non-existent host
  270. $host = FALSE;
  271. // Get host settings from configuration
  272. foreach ($this->_config['servers'] as $server)
  273. {
  274. // Merge the defaults, since they won't always be set
  275. $server += $this->_default_config;
  276. // We're looking at the failed server
  277. if ($hostname == $server['host'] and $port == $server['port'])
  278. {
  279. // Server to disable, since it failed
  280. $host = $server;
  281. continue;
  282. }
  283. }
  284. if ( ! $host)
  285. return;
  286. else
  287. {
  288. return $this->_memcache->setServerParams(
  289. $host['host'],
  290. $host['port'],
  291. $host['timeout'],
  292. $host['retry_interval'],
  293. FALSE, // Server is offline
  294. [$this, '_failed_request'
  295. ]);
  296. }
  297. }
  298. /**
  299. * Increments a given value by the step value supplied.
  300. * Useful for shared counters and other persistent integer based
  301. * tracking.
  302. *
  303. * @param string id of cache entry to increment
  304. * @param int step value to increment by
  305. * @return integer
  306. * @return boolean
  307. */
  308. public function increment($id, $step = 1)
  309. {
  310. return $this->_memcache->increment($id, $step);
  311. }
  312. /**
  313. * Decrements a given value by the step value supplied.
  314. * Useful for shared counters and other persistent integer based
  315. * tracking.
  316. *
  317. * @param string id of cache entry to decrement
  318. * @param int step value to decrement by
  319. * @return integer
  320. * @return boolean
  321. */
  322. public function decrement($id, $step = 1)
  323. {
  324. return $this->_memcache->decrement($id, $step);
  325. }
  326. }