3 namespace Friendica\Core\Cache;
5 use Friendica\BaseObject;
6 use Friendica\Core\Cache;
9 * Redis Cache Driver. This driver is based on Memcache driver
11 * @author Hypolite Petovan <mrpetovan@gmail.com>
12 * @author Roland Haeder <roland@mxchange.org>
14 class RedisCacheDriver extends BaseObject implements IMemoryCacheDriver
21 public function __construct($redis_host, $redis_port)
23 if (!class_exists('Redis', false)) {
24 throw new \Exception('Redis class isn\'t available');
27 $this->redis = new \Redis();
29 if (!$this->redis->connect($redis_host, $redis_port)) {
30 throw new \Exception('Expected Redis server at ' . $redis_host . ':' . $redis_port . ' isn\'t available');
34 public function get($key)
38 // We fetch with the hostname as key to avoid problems with other applications
39 $cached = $this->redis->get(self::getApp()->get_hostname() . ':' . $key);
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 // We store with the hostname as key to avoid problems with other applications
62 return $this->redis->setex(
63 self::getApp()->get_hostname() . ":" . $key,
68 return $this->redis->set(
69 self::getApp()->get_hostname() . ":" . $key,
75 public function delete($key)
77 return $this->redis->delete($key);
80 public function clear()
89 public function add($key, $value, $ttl = Cache::FIVE_MINUTES)
91 if (!is_int($value)) {
92 $value = serialize($value);
95 return $this->redis->setnx(self::getApp()->get_hostname() . ":" . $key, $value);
101 public function compareSet($key, $oldValue, $newValue, $ttl = Cache::FIVE_MINUTES)
103 if (!is_int($newValue)) {
104 $newValue = serialize($newValue);
107 $this->redis->watch(self::getApp()->get_hostname() . ":" . $key);
108 // If the old value isn't what we expected, somebody else changed the key meanwhile
109 if ($this->get($key) === $oldValue) {
111 $result = $this->redis->multi()
112 ->setex(self::getApp()->get_hostname() . ":" . $ttl, $key, $newValue)
115 $result = $this->redis->multi()
116 ->set(self::getApp()->get_hostname() . ":" . $key, $newValue)
119 return $result !== false;
121 $this->redis->unwatch();
127 public function compareDelete($key, $value)
129 $this->redis->watch(self::getApp()->get_hostname() . ":" . $key);
130 // If the old value isn't what we expected, somebody else changed the key meanwhile
131 if ($this->get($key) === $value) {
132 $result = $this->redis->multi()
133 ->del(self::getApp()->get_hostname() . ":" . $key)
135 return $result !== false;
137 $this->redis->unwatch();