3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
6 use Friendica\Core\Logger;
9 use Friendica\Network\HTTPException\InternalServerErrorException;
13 * Memcached Cache Driver
15 * @author Hypolite Petovan <hypolite@mrpetovan.com>
17 class MemcachedCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
20 use TraitCompareDelete;
28 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
30 * 0 => "hostname, port(, weight)",
34 * @param array $memcached_hosts
37 public function __construct(array $memcached_hosts)
39 if (!class_exists('Memcached', false)) {
40 throw new Exception('Memcached class isn\'t available');
43 $this->memcached = new Memcached();
45 array_walk($memcached_hosts, function (&$value) {
46 if (is_string($value)) {
47 $value = array_map('trim', explode(',', $value));
51 $this->memcached->addServers($memcached_hosts);
53 if (count($this->memcached->getServerList()) == 0) {
54 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
61 public function getAllKeys($prefix = null)
63 $keys = $this->getOriginalKeys($this->memcached->getAllKeys());
65 if ($this->memcached->getResultCode() == Memcached::RES_SUCCESS) {
66 return $this->filterArrayKeysByPrefix($keys, $prefix);
68 Logger::log('Memcached \'getAllKeys\' failed with ' . $this->memcached->getResultMessage(), Logger::ALL);
76 public function get($key)
79 $cachekey = $this->getCacheKey($key);
81 // We fetch with the hostname as key to avoid problems with other applications
82 $value = $this->memcached->get($cachekey);
84 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
87 Logger::log('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);