atomic_redis_cache 0.0.1 → 0.2.0
Sign up to get free protection for your applications and to get access to all the features.
- data/lib/atomic_redis_cache.rb +30 -1
- data/lib/atomic_redis_cache/version.rb +1 -1
- metadata +1 -1
data/lib/atomic_redis_cache.rb
CHANGED
@@ -25,7 +25,7 @@ module AtomicRedisCache
|
|
25
25
|
|
26
26
|
now = Time.now.to_i
|
27
27
|
ttl = expires_in + retries * race_ttl
|
28
|
-
t_key =
|
28
|
+
t_key = timer(key)
|
29
29
|
|
30
30
|
if val = redis.get(key) # cache hit
|
31
31
|
if redis.get(t_key).to_i < now # expired entry or dne
|
@@ -52,6 +52,35 @@ module AtomicRedisCache
|
|
52
52
|
Marshal.load(val)
|
53
53
|
end
|
54
54
|
|
55
|
+
def read(key)
|
56
|
+
val, exp = redis.mget key, timer(key)
|
57
|
+
Marshal.dump(val) if exp > Time.now.to_i
|
58
|
+
end
|
59
|
+
|
60
|
+
def write(key, val, opts={})
|
61
|
+
expires_in = opts[:expires_in] || DEFAULT_EXPIRATION
|
62
|
+
race_ttl = opts[:race_condition_ttl] || DEFAULT_RACE_TTL
|
63
|
+
retries = opts[:max_retries] || MAX_RETRIES
|
64
|
+
ttl = expires_in + retries * race_ttl
|
65
|
+
expiry = Time.now.to_i + expires_in
|
66
|
+
|
67
|
+
response = redis.multi do
|
68
|
+
redis.setex key, ttl, Marshal.dump(val)
|
69
|
+
redis.set timer(key), expiry
|
70
|
+
end
|
71
|
+
|
72
|
+
response.all? { |ret| ret == 'OK' }
|
73
|
+
end
|
74
|
+
|
75
|
+
def delete(key)
|
76
|
+
redis.del(key) == 1
|
77
|
+
end
|
78
|
+
|
79
|
+
def timer(key)
|
80
|
+
"timer:#{key}"
|
81
|
+
end
|
82
|
+
private :timer
|
83
|
+
|
55
84
|
def redis
|
56
85
|
raise 'AtomicRedisCache.redis must be set before use.' unless @redis
|
57
86
|
@redis.respond_to?(:call) ? @redis.call : @redis
|