forked from pingcap/discourse
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcache.rb
62 lines (48 loc) · 1.23 KB
/
cache.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
# frozen_string_literal: true
# Discourse specific cache, enforces 1 day expiry
class Cache < ActiveSupport::Cache::Store
# 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 = {})
@namespace = opts[:namespace] || "_CACHE_"
super(opts)
end
def redis
$redis
end
def reconnect
redis.reconnect
end
def keys(pattern = "*")
redis.scan_each(match: "#{@namespace}:#{pattern}").to_a
end
def clear
keys.each do |k|
redis.del(k)
end
end
def normalize_key(key, opts = nil)
"#{@namespace}:#{key}"
end
protected
def read_entry(key, options)
if data = redis.get(key)
data = Marshal.load(data)
ActiveSupport::Cache::Entry.new data
end
rescue
# corrupt cache, fail silently for now, remove rescue later
end
def write_entry(key, entry, options)
dumped = Marshal.dump(entry.value)
expiry = options[:expires_in] || MAX_CACHE_AGE
redis.setex(key, expiry, dumped)
true
end
def delete_entry(key, options)
redis.del key
end
end