Class: MemCache
Instance Method Summary collapse
- #acquire_lock(key) ⇒ Object
- #has_lock?(key) ⇒ Boolean
-
#initialize(servers = nil, options = {}) ⇒ MemCache
constructor
A new instance of MemCache.
- #lock_and_set(key, value, expiry = 0, raw = false) ⇒ Object
- #lock_key(name) ⇒ Object
- #release_lock(key) ⇒ Object
Constructor Details
#initialize(servers = nil, options = {}) ⇒ MemCache
Returns a new instance of MemCache.
75 76 77 78 79 |
# File 'lib/extensions/memcache.rb', line 75 def initialize(servers=nil, ={}) @servers = env_servers || servers || 'localhost:11211' @options = {:expires_in => 0}.merge() self.extend(Dalli::Client::MemcacheClientCompatibility) if Dalli::Client.compatibility_mode end |
Instance Method Details
#acquire_lock(key) ⇒ Object
89 90 91 92 93 94 95 96 97 98 99 100 101 |
# File 'lib/extensions/memcache.rb', line 89 def acquire_lock key @locks ||= {} return true if has_lock? key # Keep trying to add the key to memcache # Add returns false if the key is already in memcache # Add is our test-and-set operation while !add lock_key(key), 1 # We didn't get the lock, keep trying till we do Thread.pass end @locks[key] = 1 end |
#has_lock?(key) ⇒ Boolean
110 111 112 |
# File 'lib/extensions/memcache.rb', line 110 def has_lock? key @locks[key].present? end |
#lock_and_set(key, value, expiry = 0, raw = false) ⇒ Object
83 84 85 86 87 |
# File 'lib/extensions/memcache.rb', line 83 def lock_and_set key, value, expiry = 0, raw = false acquire_lock key set key, value, expiry, raw release_lock key end |
#lock_key(name) ⇒ Object
114 115 116 |
# File 'lib/extensions/memcache.rb', line 114 def lock_key name "LOCK-#{@name}" end |
#release_lock(key) ⇒ Object
103 104 105 106 107 108 |
# File 'lib/extensions/memcache.rb', line 103 def release_lock key if has_lock? key delete lock_key(key) @locks.delete key end end |