Skip to content
Snippets Groups Projects
Commit cbc54da6 authored by Kasper Weibel's avatar Kasper Weibel
Browse files

Add abstraction to the Autoexpire Cache client and add a Dalli option for Memcached

parent a1ba3757
No related branches found
No related tags found
No related merge requests found
# This class implements a cache with simple delegation to the Redis store, but # This class implements a common cache interface with simple delegation to the chosen cache store.
# when it creates a key/value pair, it also sends an EXPIRE command with a TTL.
# It should be fairly simple to do the same thing with Memcached. require 'dalli_client'
require 'redis_client'
class AutoexpireCache class AutoexpireCache
def initialize(store) def initialize(store_type = :redis, ttl = 86400)
@store = store @store = case store_type
@ttl = 86400 when :redis
RedisClient.new(ttl)
when :dalli
DalliClient.new(ttl)
else
raise 'Unknown client type'
end
end end
def [](url) def [](url)
...@@ -13,7 +21,6 @@ class AutoexpireCache ...@@ -13,7 +21,6 @@ class AutoexpireCache
def []=(url, value) def []=(url, value)
@store.[]=(url, value) @store.[]=(url, value)
@store.expire(url, @ttl)
end end
def keys def keys
...@@ -25,4 +32,4 @@ class AutoexpireCache ...@@ -25,4 +32,4 @@ class AutoexpireCache
end end
end end
Geocoder.configure(:cache => AutoexpireCache.new(Redis.new)) Geocoder.configure(:cache => AutoexpireCache.new)
# gem install dalli
require 'dalli/client'
require 'yaml'
class DalliClient
# Setup Dalli as on Heroku using the Memcachier gem.
# On other setups you'll have to specify your Memcached server
def initialize(ttl = 86400)
@keys = 'GeocoderDalliClientKeys'
@store = Dalli::Client.new(:expires_in => ttl)
end
def [](key)
res = @store.get(key)
res = YAML::load(res) if res.present?
res
end
def []=(key, value)
if value.nil?
del(key)
else
key_cache_add(key) if @store.add(key, YAML::dump(value))
end
value
end
def keys
key_cache
end
def del(key)
key_cache_delete(key) if @store.delete(key)
end
private
def key_cache
the_keys = @store.get(@keys)
if the_keys.nil?
@store.add(@keys, YAML::dump([]))
[]
else
YAML::load(the_keys)
end
end
def key_cache_add(key)
@store.replace(@keys, YAML::dump(key_cache << key))
end
def key_cache_delete(key)
tmp = key_cache
tmp.delete(key)
@store.replace(@keys, YAML::dump(tmp))
end
end
# This class implements a cache with simple delegation to the Redis store, but
# when it creates a key/value pair, it also sends an EXPIRE command with a TTL.
# It should be fairly simple to do the same thing with Memcached.
class RedisClient
def initialize(ttl = 86400)
@store = Redis.new
@ttl = ttl
end
def [](url)
@store.[](url)
end
def []=(url, value)
@store.[]=(url, value)
@store.expire(url, @ttl)
end
def keys
@store.keys
end
def del(url)
@store.del(url)
end
end
\ No newline at end of file
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment