3 namespace Friendica\Core\Cache;
6 use Friendica\Core\BaseCache;
7 use Friendica\Core\Config\IConfig;
9 use Psr\Log\LoggerInterface;
14 * @author Hypolite Petovan <hypolite@mrpetovan.com>
16 class MemcachedCache extends BaseCache implements IMemoryCache
19 use TraitCompareDelete;
20 use TraitMemcacheCommand;
28 * @var LoggerInterface
33 * Due to limitations of the INI format, the expected configuration for Memcached servers is the following:
35 * 0 => "hostname, port(, weight)",
39 * @param array $memcached_hosts
43 public function __construct(string $hostname, IConfig $config, LoggerInterface $logger)
45 if (!class_exists('Memcached', false)) {
46 throw new Exception('Memcached class isn\'t available');
49 parent::__construct($hostname);
51 $this->logger = $logger;
53 $this->memcached = new Memcached();
55 $memcached_hosts = $config->get('system', 'memcached_hosts');
57 array_walk($memcached_hosts, function (&$value) {
58 if (is_string($value)) {
59 $value = array_map('trim', explode(',', $value));
63 $this->server = $memcached_hosts[0][0] ?? 'localhost';
64 $this->port = $memcached_hosts[0][1] ?? 11211;
66 $this->memcached->addServers($memcached_hosts);
68 if (count($this->memcached->getServerList()) == 0) {
69 throw new Exception('Expected Memcached servers aren\'t available, config:' . var_export($memcached_hosts, true));
76 public function getAllKeys($prefix = null)
78 $keys = $this->getOriginalKeys($this->getMemcacheKeys());
80 return $this->filterArrayKeysByPrefix($keys, $prefix);
86 public function get($key)
89 $cachekey = $this->getCacheKey($key);
91 // We fetch with the hostname as key to avoid problems with other applications
92 $value = $this->memcached->get($cachekey);
94 if ($this->memcached->getResultCode() === Memcached::RES_SUCCESS) {
97 $this->logger->debug('Memcached \'get\' failed', ['result' => $this->memcached->getResultMessage()]);
106 public function set($key, $value, $ttl = Duration::FIVE_MINUTES)
108 $cachekey = $this->getCacheKey($key);
110 // We store with the hostname as key to avoid problems with other applications
112 return $this->memcached->set(
118 return $this->memcached->set(
128 public function delete($key)
130 $cachekey = $this->getCacheKey($key);
131 return $this->memcached->delete($cachekey);
137 public function clear($outdated = true)
142 return $this->memcached->flush();
149 public function add($key, $value, $ttl = Duration::FIVE_MINUTES)
151 $cachekey = $this->getCacheKey($key);
152 return $this->memcached->add($cachekey, $value, $ttl);
158 public function getName()
160 return Type::MEMCACHED;