2015-02-19 13:58:05 +08:00
|
|
|
# Discourse specific cache, enforces 1 day expiry
|
2013-05-13 16:04:03 +08:00
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
class Cache < ActiveSupport::Cache::Store
|
|
|
|
|
2015-02-19 13:58:05 +08:00
|
|
|
# nothing is cached for longer than 1 day EVER
|
|
|
|
# there is no reason to have data older than this clogging redis
|
|
|
|
# it is dangerous cause if we rename keys we will be stuck with
|
|
|
|
# pointless data
|
|
|
|
MAX_CACHE_AGE = 1.day unless defined? MAX_CACHE_AGE
|
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
def initialize(opts = {})
|
2015-02-19 13:58:05 +08:00
|
|
|
@namespace = opts[:namespace] || "_CACHE_"
|
2014-01-06 13:50:04 +08:00
|
|
|
super(opts)
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
def redis
|
2014-01-06 13:50:04 +08:00
|
|
|
$redis
|
|
|
|
end
|
|
|
|
|
|
|
|
def reconnect
|
|
|
|
redis.reconnect
|
|
|
|
end
|
|
|
|
|
|
|
|
def clear
|
2015-02-19 13:58:05 +08:00
|
|
|
redis.keys("#{@namespace}:*").each do |k|
|
|
|
|
redis.del(k)
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
2014-01-06 13:50:04 +08:00
|
|
|
end
|
2013-05-13 16:04:03 +08:00
|
|
|
|
2017-08-31 12:06:56 +08:00
|
|
|
def normalize_key(key, opts = nil)
|
2015-02-19 13:58:05 +08:00
|
|
|
"#{@namespace}:" << key
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
protected
|
|
|
|
|
|
|
|
def read_entry(key, options)
|
|
|
|
if data = redis.get(key)
|
2014-01-07 14:36:47 +08:00
|
|
|
data = Marshal.load(data)
|
2014-01-06 13:50:04 +08:00
|
|
|
ActiveSupport::Cache::Entry.new data
|
|
|
|
end
|
2014-01-07 14:36:47 +08:00
|
|
|
rescue
|
|
|
|
# corrupt cache, fail silently for now, remove rescue later
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
2014-01-06 13:50:04 +08:00
|
|
|
def write_entry(key, entry, options)
|
2014-01-07 14:36:47 +08:00
|
|
|
dumped = Marshal.dump(entry.value)
|
2015-02-19 13:58:05 +08:00
|
|
|
expiry = options[:expires_in] || MAX_CACHE_AGE
|
|
|
|
redis.setex(key, expiry, dumped)
|
2014-01-06 13:50:04 +08:00
|
|
|
true
|
|
|
|
end
|
|
|
|
|
|
|
|
def delete_entry(key, options)
|
|
|
|
redis.del key
|
2013-05-13 16:04:03 +08:00
|
|
|
end
|
|
|
|
|
|
|
|
end
|