3 namespace Friendica\Core\Cache;
6 use Friendica\Core\Cache;
10 * Redis Cache Driver. This driver is based on Memcache driver
12 * @author Hypolite Petovan <hypolite@mrpetovan.com>
13 * @author Roland Haeder <roland@mxchange.org>
15 class RedisCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
23 * @param string $redis_host
24 * @param int $redis_port
27 public function __construct($redis_host, $redis_port)
29 if (!class_exists('Redis', false)) {
30 throw new Exception('Redis class isn\'t available');
33 $this->redis = new Redis();
35 if (!$this->redis->connect($redis_host, $redis_port)) {
36 throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
43 public function getAllKeys($prefix = null)
48 $search = $prefix . '*';
51 $list = $this->redis->keys($this->getCacheKey($search));
53 return $this->getOriginalKeys($list);
59 public function get($key)
62 $cachekey = $this->getCacheKey($key);
64 $cached = $this->redis->get($cachekey);
65 if ($cached === false && !$this->redis->exists($cachekey)) {
69 $value = unserialize($cached);
71 // Only return a value if the serialized value is valid.
72 // We also check if the db entry is a serialized
73 // boolean 'false' value (which we want to return).
74 if ($cached === serialize(false) || $value !== false) {
84 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
86 $cachekey = $this->getCacheKey($key);
88 $cached = serialize($value);
91 return $this->redis->setex(
97 return $this->redis->set(
107 public function delete($key)
109 $cachekey = $this->getCacheKey($key);
110 return ($this->redis->delete($cachekey) > 0);
116 public function clear($outdated = true)
121 return $this->redis->flushAll();
128 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
130 $cachekey = $this->getCacheKey($key);
131 $cached = serialize($value);
133 return $this->redis->setnx($cachekey, $cached);
139 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
141 $cachekey = $this->getCacheKey($key);
143 $newCached = serialize($newValue);
145 $this->redis->watch($cachekey);
146 // If the old value isn't what we expected, somebody else changed the key meanwhile
147 if ($this->get($key) === $oldValue) {
149 $result = $this->redis->multi()
150 ->setex($cachekey, $ttl, $newCached)
153 $result = $this->redis->multi()
154 ->set($cachekey, $newCached)
157 return $result !== false;
159 $this->redis->unwatch();
166 public function compareDelete($key, $value)
168 $cachekey = $this->getCacheKey($key);
170 $this->redis->watch($cachekey);
171 // If the old value isn't what we expected, somebody else changed the key meanwhile
172 if ($this->get($key) === $value) {
173 $result = $this->redis->multi()
176 return $result !== false;
178 $this->redis->unwatch();