Skip to content

Instantly share code, notes, and snippets.

@mloughran
Created November 4, 2011 19:36
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save mloughran/1340275 to your computer and use it in GitHub Desktop.
Save mloughran/1340275 to your computer and use it in GitHub Desktop.
Proof of concept Redis cache, which blocks fiber if required on access
require 'eventmachine'
require 'em-hiredis'
require 'fiber'
class Cache
include EM::Deferrable
def initialize(key)
$redis.get(key) { |v|
@value = v
succeed
}
end
def value
if @value
puts "Returning cached value"
@value
else
puts "Blocking the current fiber till result"
start = Time.now
f = Fiber.current
callback {
puts "Fiber blocked for #{Time.now - start}s"
f.resume(@value)
}
return Fiber.yield
end
end
end
EM.run {
$redis = EM::Hiredis.connect
Fiber.new {
$redis.set('foo', 'hello folks')
c = Cache.new('foo')
p c.value # Not populated yet - will block fiber
EM.add_timer(1) {
p c.value # Will return from cache
}
}.resume
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment