3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
11 * Redis Cache Driver. This driver is based on Memcache driver
13 * @author Hypolite Petovan <hypolite@mrpetovan.com>
14 * @author Roland Haeder <roland@mxchange.org>
16 class RedisCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
24 * @param string $redis_host
25 * @param int $redis_port
28 public function __construct($redis_host, $redis_port)
30 if (!class_exists('Redis', false)) {
31 throw new Exception('Redis class isn\'t available');
34 $this->redis = new Redis();
36 if (!$this->redis->connect($redis_host, $redis_port)) {
37 throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
44 public function getAllKeys($prefix = null)
49 $search = $prefix . '*';
52 $list = $this->redis->keys($this->getCacheKey($search));
54 return $this->getOriginalKeys($list);
60 public function get($key)
63 $cachekey = $this->getCacheKey($key);
65 $cached = $this->redis->get($cachekey);
66 if ($cached === false && !$this->redis->exists($cachekey)) {
70 $value = unserialize($cached);
72 // Only return a value if the serialized value is valid.
73 // We also check if the db entry is a serialized
74 // boolean 'false' value (which we want to return).
75 if ($cached === serialize(false) || $value !== false) {
85 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
87 $cachekey = $this->getCacheKey($key);
89 $cached = serialize($value);
92 return $this->redis->setex(
98 return $this->redis->set(
108 public function delete($key)
110 $cachekey = $this->getCacheKey($key);
111 return ($this->redis->delete($cachekey) > 0);
117 public function clear($outdated = true)
122 return $this->redis->flushAll();
129 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
131 $cachekey = $this->getCacheKey($key);
132 $cached = serialize($value);
134 return $this->redis->setnx($cachekey, $cached);
140 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
142 $cachekey = $this->getCacheKey($key);
144 $newCached = serialize($newValue);
146 $this->redis->watch($cachekey);
147 // If the old value isn't what we expected, somebody else changed the key meanwhile
148 if ($this->get($key) === $oldValue) {
150 $result = $this->redis->multi()
151 ->setex($cachekey, $ttl, $newCached)
154 $result = $this->redis->multi()
155 ->set($cachekey, $newValue)
158 return $result !== false;
160 $this->redis->unwatch();
167 public function compareDelete($key, $value)
169 $cachekey = $this->getCacheKey($key);
171 $this->redis->watch($cachekey);
172 // If the old value isn't what we expected, somebody else changed the key meanwhile
173 if ($this->get($key) === $value) {
174 $result = $this->redis->multi()
177 return $result !== false;
179 $this->redis->unwatch();