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()
52 public function get($key)
55 $cachekey = $this->getCacheKey($key);
57 $cached = $this->redis->get($cachekey);
58 if ($cached === false && !$this->redis->exists($cachekey)) {
62 $value = unserialize($cached);
64 // Only return a value if the serialized value is valid.
65 // We also check if the db entry is a serialized
66 // boolean 'false' value (which we want to return).
67 if ($cached === serialize(false) || $value !== false) {
77 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
79 $cachekey = $this->getCacheKey($key);
81 $cached = serialize($value);
84 return $this->redis->setex(
90 return $this->redis->set(
100 public function delete($key)
102 $cachekey = $this->getCacheKey($key);
103 return ($this->redis->delete($cachekey) > 0);
109 public function clear($outdated = true)
114 return $this->redis->flushAll();
121 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
123 $cachekey = $this->getCacheKey($key);
124 $cached = serialize($value);
126 return $this->redis->setnx($cachekey, $cached);
132 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
134 $cachekey = $this->getCacheKey($key);
136 $newCached = serialize($newValue);
138 $this->redis->watch($cachekey);
139 // If the old value isn't what we expected, somebody else changed the key meanwhile
140 if ($this->get($key) === $oldValue) {
142 $result = $this->redis->multi()
143 ->setex($cachekey, $ttl, $newCached)
146 $result = $this->redis->multi()
147 ->set($cachekey, $newValue)
150 return $result !== false;
152 $this->redis->unwatch();
159 public function compareDelete($key, $value)
161 $cachekey = $this->getCacheKey($key);
163 $this->redis->watch($cachekey);
164 // If the old value isn't what we expected, somebody else changed the key meanwhile
165 if ($this->get($key) === $value) {
166 $result = $this->redis->multi()
169 return $result !== false;
171 $this->redis->unwatch();