3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
8 use Friendica\Network\HTTPException\InternalServerErrorException;
12 * Memcached Cache Driver
14 * @author Hypolite Petovan <hypolite@mrpetovan.com>
16 class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
19 use TraitCompareDelete;
27 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
29 * 0 => "hostname, port(, weight)",
33 * @param array $memcached_hosts
36 public function __construct(array $memcached_hosts)
38 if (!class_exists('Memcached', false)) {
39 throw new Exception('Memcached class isn\'t available');
42 $this->memcached = new Memcached();
45 $this->memcached->setOption(Memcached::OPT_BINARY_PROTOCOL, false);
47 array_walk($memcached_hosts, function (&$value) {
48 if (is_string($value)) {
49 $value = array_map('trim', explode(',', $value));
53 $this->memcached->addServers($memcached_hosts);
55 if (count($this->memcached->getServerList()) == 0) {
56 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
63 public function getAllKeys($prefix = null)
65 $keys = $this->getOriginalKeys($this->memcached->getAllKeys());
67 if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) {
68 return $this->filterArrayKeysByPrefix($keys, $prefix);
70 logger('Memcached \'getAllKeys\' failed with ' . $this->memcached->getResultMessage(), LOGGER_ALL);
78 public function get($key)
80 $cachekey = $this->getCacheKey($key);
82 // We fetch with the hostname as key to avoid problems with other applications
83 $value = $this->memcached->get($cachekey);
85 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
88 logger('Memcached \'get\' failed with ' . $this->memcached->getResultMessage(), LOGGER_ALL);
96 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
98 $cachekey = $this->getCacheKey($key);
100 // We store with the hostname as key to avoid problems with other applications
102 return $this->memcached->set(
108 return $this->memcached->set(
118 public function delete($key)
120 $cachekey = $this->getCacheKey($key);
121 return $this->memcached->delete($cachekey);
127 public function clear($outdated = true)
132 return $this->memcached->flush();
139 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
141 $cachekey = $this->getCacheKey($key);
142 return $this->memcached->add($cachekey, $value, $ttl);