Created
May 3, 2012 06:10
-
-
Save mvastola/2583659 to your computer and use it in GitHub Desktop.
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 'dalli' | |
module App | |
class Settings | |
class << self | |
attr_accessor :cache_ttl, :fetch_timeout, :fetch_attempt_interval | |
end | |
end | |
class Cache | |
class << self | |
def fetch(name, &block) | |
start = Time.now | |
while Time.now - start < Settings.fetch_timeout do | |
value = get(name) || lock_and_block(name, &block) | |
return value if value | |
Kernel.sleep Settings.fetch_attempt_interval | |
end | |
nil | |
end | |
def reset! | |
!@dalli || @dalli.reset | |
true | |
end | |
private | |
def dalli | |
return @dalli if @dalli | |
@dalli = Dalli::Client.new('localhost:11211', { | |
:namespace => "blah", | |
:failover => false, | |
:compress => true, | |
:value_max_bytes => 1024 * 1024 * 10 # 10MB | |
}) | |
end | |
def get(*args) | |
dalli.get(*args) | |
end | |
def add(*args) | |
dalli.add(*args) | |
end | |
def delete(*args) | |
dalli.delete(*args) | |
end | |
def lock_and_block(name, &block) | |
return unless add("#{name.to_s}-lock", true, Settings.fetch_timeout) | |
value = yield | |
add(name, value, Settings.cache_ttl) | |
delete("#{name.to_s}-lock") | |
value | |
end | |
end | |
end | |
end | |
if defined?(PhusionPassenger) | |
PhusionPassenger.on_event(:starting_worker_process) do |forked| | |
App::Cache.reset! if forked | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment