Skip to content

Instantly share code, notes, and snippets.

@jeffomatic
Created April 29, 2012 03:07
Show Gist options
  • Save jeffomatic/2527662 to your computer and use it in GitHub Desktop.
Save jeffomatic/2527662 to your computer and use it in GitHub Desktop.
Blog: Redis as a mutex service, Code: cache_lookup
# CAVEAT EMPTOR: This is excerpted code that I pulled out of context,
# re-arranged, renamed the variables of, and otherwise dicked around with
# a lot without having put it back into a Ruby interpreter, so it's
# possible that there's some gnarly typo or bug in here. In short, don't
# cut-and-paste this code.
# In our example, "cache" is some resource accessible by all of our
# processes and provides a run-time interface similar to Ruby's Hash
# class.
def cache_lookup(redis, resource_handle, cache, &run_on_cache_miss)
begin
cache.fetch(resource_handle)
rescue KeyError
redis_spinlock(redis, resource_handle) do |spin_count|
if spin_count > 0
# We had to wait before acquiring the lock, which means something
# probably is in the cache now. We should check the cache again.
begin
return cache.fetch(resource_handle)
rescue KeyError
# do nothing
end
cache[resource_handle] = run_on_cache_miss.call
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment