3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
11 * Memcache Cache Driver
13 * @author Hypolite Petovan <hypolite@mrpetovan.com>
15 class MemcacheCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
18 use TraitCompareDelete;
26 * @param string $memcache_host
27 * @param int $memcache_port
30 public function __construct($memcache_host, $memcache_port)
32 if (!class_exists('Memcache', false)) {
33 throw new Exception('Memcache class isn\'t available');
36 $this->memcache = new Memcache();
38 if (!$this->memcache->connect($memcache_host, $memcache_port)) {
39 throw new Exception('Expected Memcache server at ' . $memcache_host . ':' . $memcache_port . ' isn\'t available');
46 public function getAllKeys($prefix = null)
49 $allSlabs = $this->memcache->getExtendedStats('slabs');
50 foreach ($allSlabs as $slabs) {
51 foreach (array_keys($slabs) as $slabId) {
52 $cachedump = $this->memcache->getExtendedStats('cachedump', (int)$slabId);
53 foreach ($cachedump as $key => $arrVal) {
54 if (!is_array($arrVal)) {
57 $keys = array_merge($keys, array_keys($arrVal));
62 $keys = $this->getOriginalKeys($keys);
64 return $this->filterArrayKeysByPrefix($keys, $prefix);
70 public function get($key)
73 $cachekey = $this->getCacheKey($key);
75 // We fetch with the hostname as key to avoid problems with other applications
76 $cached = $this->memcache->get($cachekey);
78 // @see http://php.net/manual/en/memcache.get.php#84275
79 if (is_bool($cached) || is_double($cached) || is_long($cached)) {
83 $value = @unserialize($cached);
85 // Only return a value if the serialized value is valid.
86 // We also check if the db entry is a serialized
87 // boolean 'false' value (which we want to return).
88 if ($cached === serialize(false) || $value !== false) {
98 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
100 $cachekey = $this->getCacheKey($key);
102 // We store with the hostname as key to avoid problems with other applications
104 return $this->memcache->set(
111 return $this->memcache->set(
122 public function delete($key)
124 $cachekey = $this->getCacheKey($key);
125 return $this->memcache->delete($cachekey);
131 public function clear($outdated = true)
136 return $this->memcache->flush();
143 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
145 $cachekey = $this->getCacheKey($key);
146 return $this->memcache->add($cachekey, serialize($value), MEMCACHE_COMPRESSED, $ttl);