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
23 public function __construct($redis_host, $redis_port)
25 if (!class_exists('Redis', false)) {
26 throw new Exception('Redis class isn\'t available');
29 $this->redis = new Redis();
31 if (!$this->redis->connect($redis_host, $redis_port)) {
32 throw new Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
36 public function get($key)
39 $cachekey = $this->getCacheKey($key);
41 $cached = $this->redis->get($cachekey);
42 if ($cached === false && !$this->redis->exists($cachekey)) {
46 $value = unserialize($cached);
48 // Only return a value if the serialized value is valid.
49 // We also check if the db entry is a serialized
50 // boolean 'false' value (which we want to return).
51 if ($cached === serialize(false) || $value !== false) {
58 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
60 $cachekey = $this->getCacheKey($key);
62 $cached = serialize($value);
65 return $this->redis->setex(
71 return $this->redis->set(
78 public function delete($key)
80 $cachekey = $this->getCacheKey($key);
81 return ($this->redis->delete($cachekey) > 0);
84 public function clear($outdated = true)
89 return $this->redis->flushAll();
96 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
98 $cachekey = $this->getCacheKey($key);
99 $cached = serialize($value);
101 return $this->redis->setnx($cachekey, $cached);
107 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
109 $cachekey = $this->getCacheKey($key);
111 $newCached = serialize($newValue);
113 $this->redis->watch($cachekey);
114 // If the old value isn't what we expected, somebody else changed the key meanwhile
115 if ($this->get($key) === $oldValue) {
117 $result = $this->redis->multi()
118 ->setex($cachekey, $ttl, $newCached)
121 $result = $this->redis->multi()
122 ->set($cachekey, $newValue)
125 return $result !== false;
127 $this->redis->unwatch();
133 public function compareDelete($key, $value)
135 $cachekey = $this->getCacheKey($key);
137 $this->redis->watch($cachekey);
138 // If the old value isn't what we expected, somebody else changed the key meanwhile
139 if ($this->get($key) === $value) {
140 $result = $this->redis->multi()
143 return $result !== false;
145 $this->redis->unwatch();