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 // We fetch with the hostname as key to avoid problems with other applications
39 $cached = $this->redis->get($cachekey);
41 // @see http://php.net/manual/en/redis.get.php#84275
42 if (is_bool($cached) || is_double($cached) || is_long($cached)) {
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 // We store with the hostname as key to avoid problems with other applications
64 return $this->redis->setex(
70 return $this->redis->set(
77 public function delete($key)
79 return $this->redis->delete($key);
82 public function clear()
91 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
93 $cachekey = $this->getCacheKey($key);
95 if (!is_int($value)) {
96 $value = serialize($value);
99 return $this->redis->setnx($cachekey, $value);
105 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
107 $cachekey = $this->getCacheKey($key);
109 if (!is_int($newValue)) {
110 $newValue = 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($cachekey) === $oldValue) {
117 $result = $this->redis->multi()
118 ->setex($cachekey, $ttl, $newValue)
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();