forked from mikejarema/facebook-friend-rank
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcacheable_lookup.rb
74 lines (63 loc) · 1.89 KB
/
cacheable_lookup.rb
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
require 'goliath'
require 'dalli'
require 'em-synchrony'
class EventMachine::Synchrony::ConnectionPool
attr_accessor :reserved, :available, :pending
end
# CacheableLookup
# ===============
#
# This is an abstract class giving goliath handlers easy access to a memcache
# client using the instance variable 'cache'.
#
# CacheableLookup will intercept the 'force' param and if set will force all cache
# calls to bypass the the cache.
#
class CacheableLookup < Goliath::API
CACHE_TTL = 60 * 60 # 1 hour
# DummyClient says 'nil' to everything
class DummyClient
def method_missing(*args); nil; end
def get_multi(*args) {}; end
def respond_to?(*args); nil; end
end
# DalliWrapper is tolerant of failed gets & sets
class DalliWrapper < Dalli::Client
def get(key, options=nil)
super(key, options)
rescue Exception => e
puts "Memcache failed: #{e.class} (#{e.message})"
nil
end
def get_multi(*keys)
super(*keys)
rescue Exception => e
puts "Memcache failed: #{e.class} (#{e.message})"
{}
end
def set(key, value, ttl=nil, options=nil)
super(key, value, ttl, options)
rescue Exception => e
puts "Memcache failed: #{e.class} (#{e.message})"
nil
end
end
@@cache_pool = EventMachine::Synchrony::ConnectionPool.new(size: 20) do
# NOTE: in development the MEMCACHIER references nil out (assumes localhost & unauthenticated cache)
DalliWrapper.new(
ENV['MEMCACHIER_SERVERS'],
username: ENV['MEMCACHIER_USERNAME'], password: ENV['MEMCACHIER_PASSWORD'], :expires_in => CACHE_TTL,
async: false # <-- NOTE: async disabled, it doesn't work in a Fiber (as req'd by people_rank.rb)
)
end
def cache
if !params['force']
@@cache_pool
else
@dummy_cache ||= DummyClient.new
end
end
def self.cache_pool
@@cache_pool
end
end