Skip to content

Instantly share code, notes, and snippets.

@akahigeg
Created September 17, 2011 06:06
Show Gist options
  • Save akahigeg/1223677 to your computer and use it in GitHub Desktop.
Save akahigeg/1223677 to your computer and use it in GitHub Desktop.
Amazon::Ecs response caching to memcached
# -*- coding: utf-8 -*-
require 'amazon/ecs'
require 'dalli'
require 'active_support/core_ext'
module Amazon
class Ecs
class << self
def send_request_with_memcache(opts)
opts = options.merge(opts) if options
begin
if content = get_content_from_memcache(opts)
response = Response.new(content)
else
response = send_request_without_memcache(opts)
dalli_client.set(memcache_key(opts), response.doc.to_xml)
end
rescue Dalli::RingError
# nocache silently
end
response
end
alias_method_chain :send_request, :memcache
def dalli_client
@dc ||= Dalli::Client.new('localhost:11211')
end
def get_content_from_memcache(opts)
if %w{ItemSearch ItemLookup SimilarLookup}.include? opts[:operation]
dalli_client.get(memcache_key(opts))
else
nil
end
end
def memcache_key(opts)
o = opts.dup
ignore_options_key_for_memcache.each do |key|
o.delete(key)
end
CGI.escape(o.sort.join('-').gsub(/\s/, '%2F'))
end
# to keep memcache key short
def ignore_options_key_for_memcache
[:service, :version, :AWS_access_key_id, :AWS_secret_key, :associate_tag]
end
end
end
end
# -*- coding: utf-8 -*-
require 'amazon_ecs_with_memcache.rb'
describe "Amazon::Ecs" do
describe "send_request_with_memcache" do
let(:request_opts) do
Amazon::Ecs.options.merge({:Title => 'Rails', :search_index => 'Books', :operation => 'ItemSearch'})
end
let(:dc) { Dalli::Client.new('localhost:11211') }
before do
dc.delete(Amazon::Ecs.memcache_key(request_opts))
@res = Amazon::Ecs.item_search('Rails', :type => 'Title', :search_index => 'Books')
end
describe "request" do
subject {@res}
it { should be_is_valid_request }
its(:error) { should be_nil }
its(:items) { should have(10).items }
end
describe "memcache" do
subject {dc.get(Amazon::Ecs.memcache_key(request_opts))}
it { should_not == nil }
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment