Files
discourse/lib/cache.rb
T

61 lines
1.2 KiB
Ruby
Raw Normal View History

2015-02-19 16:58:05 +11:00
# Discourse specific cache, enforces 1 day expiry
class Cache < ActiveSupport::Cache::Store
2015-02-19 16:58:05 +11: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
def initialize(opts = {})
2015-02-19 16:58:05 +11:00
@namespace = opts[:namespace] || "_CACHE_"
super(opts)
end
def redis
$redis
end
def reconnect
redis.reconnect
end
def keys(pattern = "*")
2018-12-15 08:53:52 +08:00
redis.scan_each(match: "#{@namespace}:#{pattern}").to_a
end
def clear
keys.each do |k|
2015-02-19 16:58:05 +11:00
redis.del(k)
end
end
def normalize_key(key, opts = nil)
2015-02-19 16:58:05 +11:00
"#{@namespace}:" << key
end
protected
def read_entry(key, options)
if data = redis.get(key)
2014-01-07 17:36:47 +11:00
data = Marshal.load(data)
ActiveSupport::Cache::Entry.new data
end
2014-01-07 17:36:47 +11:00
rescue
# corrupt cache, fail silently for now, remove rescue later
end
def write_entry(key, entry, options)
2014-01-07 17:36:47 +11:00
dumped = Marshal.dump(entry.value)
2015-02-19 16:58:05 +11:00
expiry = options[:expires_in] || MAX_CACHE_AGE
redis.setex(key, expiry, dumped)
true
end
def delete_entry(key, options)
redis.del key
end
end