Created
November 4, 2011 19:36
-
-
Save mloughran/1340275 to your computer and use it in GitHub Desktop.
Proof of concept Redis cache, which blocks fiber if required on access
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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