Permalink
Browse files

Merge pull request #14 from sorah/fetch-with-cache

Fetch with cache on redis
  • Loading branch information...
rosylilly committed Oct 31, 2015
2 parents a172c13 + 749dd75 commit bef304f431ce700fec10f05571a8689fd9cb4cd2
Showing with 19 additions and 1 deletion.
  1. +19 −1 5f/webapp/ruby/app.rb
View
@@ -82,11 +82,29 @@ def self.get(name)
def initialize(name, method, token_type, token_key, uri, mode = :http)
@name, @method, @token_type, @token_key, @uri, @mode = name, method, token_type, token_key, uri, mode
@ssl = uri.start_with?('https://')
@cachable = @token_type.nil? && @method == 'GET'
LIST[@name] = self
end
attr_reader :name, :method, :token_type, :token_key, :uri
def fetch_with_cache(conf, redis)
return fetch(conf) unless @cachable
params = (conf['params'] && conf['params'].dup) || {}
hash = Digest::MD5.hexdigest(sprintf(uri, *conf['keys']))
cached = redis.get("api/cache/#{hash}")
if cached
MessagePack.unpack(cached)
else
res = fetch(conf)
redis.set("api/cache/#{hash}", res.to_msgpack)
res
end
end
def fetch(conf)
headers = {}
params = (conf['params'] && conf['params'].dup) || {}
@@ -390,7 +408,7 @@ def fetch_api(method, uri, headers, params)
data = arg.map do |service, conf|
Expeditor::Command.new do
endpoint = Isucon5f::Endpoint.get(service)
{"service" => service, "data" => endpoint.fetch(conf)}
{"service" => service, "data" => endpoint.fetch_with_cache(conf, redis)}
end
end

0 comments on commit bef304f

Please sign in to comment.