3 namespace Friendica\Core\Cache;
5 use Friendica\Core\Cache;
8 * Redis Cache Driver. This driver is based on Memcache driver
10 * @author Hypolite Petovan <mrpetovan@gmail.com>
11 * @author Roland Haeder <roland@mxchange.org>
13 class RedisCacheDriver extends AbstractCacheDriver implements IMemoryCacheDriver
20 public function __construct($redis_host, $redis_port)
22 if (!class_exists('Redis', false)) {
23 throw new \Exception('Redis class isn\'t available');
26 $this->redis = new \Redis();
28 if (!$this->redis->connect($redis_host, $redis_port)) {
29 throw new \Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
33 public function get($key)
36 $cachekey = $this->getCacheKey($key);
38 $cached = $this->redis->get($cachekey);
39 if ($cached === false && !$this->redis->exists($cachekey)) {
43 $value = json_decode($cached);
45 // Only return a value if the serialized value is valid.
46 // We also check if the db entry is a serialized
47 // boolean 'false' value (which we want to return).
48 if ($cached === serialize(false) || $value !== false) {
55 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
57 $cachekey = $this->getCacheKey($key);
59 $cached = json_encode($value);
62 return $this->redis->setex(
68 return $this->redis->set(
75 public function delete($key)
77 $cachekey = $this->getCacheKey($key);
78 return ($this->redis->delete($cachekey) > 0);
81 public function clear($outdated = true)
86 return $this->redis->flushAll();
93 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
95 $cachekey = $this->getCacheKey($key);
96 $cached = json_encode($value);
98 return $this->redis->setnx($cachekey, $cached);
104 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
106 $cachekey = $this->getCacheKey($key);
108 $newCached = json_encode($newValue);
110 $this->redis->watch($cachekey);
111 // If the old value isn't what we expected, somebody else changed the key meanwhile
112 if ($this->get($key) === $oldValue) {
114 $result = $this->redis->multi()
115 ->setex($cachekey, $ttl, $newCached)
118 $result = $this->redis->multi()
119 ->set($cachekey, $newValue)
122 return $result !== false;
124 $this->redis->unwatch();
130 public function compareDelete($key, $value)
132 $cachekey = $this->getCacheKey($key);
134 $this->redis->watch($cachekey);
135 // If the old value isn't what we expected, somebody else changed the key meanwhile
136 if ($this->get($key) === $value) {
137 $result = $this->redis->multi()
140 return $result !== false;
142 $this->redis->unwatch();