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 get($key)
47 $cachekey = $this->getCacheKey($key);
49 $cached = $this->redis->get($cachekey);
50 if ($cached === false && !$this->redis->exists($cachekey)) {
54 $value = unserialize($cached);
56 // Only return a value if the serialized value is valid.
57 // We also check if the db entry is a serialized
58 // boolean 'false' value (which we want to return).
59 if ($cached === serialize(false) || $value !== false) {
69 public function set($key, $value, $ttl = Cache::FIVE_MINUTES)
71 $cachekey = $this->getCacheKey($key);
73 $cached = serialize($value);
76 return $this->redis->setex(
82 return $this->redis->set(
92 public function delete($key)
94 $cachekey = $this->getCacheKey($key);
95 return ($this->redis->delete($cachekey) > 0);
101 public function clear($outdated = true)
106 return $this->redis->flushAll();
113 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
115 $cachekey = $this->getCacheKey($key);
116 $cached = serialize($value);
118 return $this->redis->setnx($cachekey, $cached);
124 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
126 $cachekey = $this->getCacheKey($key);
128 $newCached = serialize($newValue);
130 $this->redis->watch($cachekey);
131 // If the old value isn't what we expected, somebody else changed the key meanwhile
132 if ($this->get($key) === $oldValue) {
134 $result = $this->redis->multi()
135 ->setex($cachekey, $ttl, $newCached)
138 $result = $this->redis->multi()
139 ->set($cachekey, $newValue)
142 return $result !== false;
144 $this->redis->unwatch();
151 public function compareDelete($key, $value)
153 $cachekey = $this->getCacheKey($key);
155 $this->redis->watch($cachekey);
156 // If the old value isn't what we expected, somebody else changed the key meanwhile
157 if ($this->get($key) === $value) {
158 $result = $this->redis->multi()
161 return $result !== false;
163 $this->redis->unwatch();