Class: Dalli::Client
Instance Method Summary collapse
- #acquire_lock(key) ⇒ Object
- #has_lock?(key) ⇒ Boolean
-
#initialize(servers = nil, options = {}) ⇒ Client
constructor
A new instance of Client.
- #lock_and_set(key, value, expiry = 0, raw = false) ⇒ Object
- #lock_key(name) ⇒ Object
-
#perform(op, key, *args) ⇒ Object
Chokepoint method for instrumentation.
- #release_lock(key) ⇒ Object
Constructor Details
#initialize(servers = nil, options = {}) ⇒ Client
Returns a new instance of Client.
4 5 6 7 8 |
# File 'lib/extensions/memcache.rb', line 4 def initialize(servers=nil, ={}) @servers = env_servers || servers || 'localhost:11211' = {:expires_in => 0}.merge() self.extend(Dalli::Client::MemcacheClientCompatibility) if Dalli::Client.compatibility_mode end |
Instance Method Details
#acquire_lock(key) ⇒ Object
18 19 20 21 22 23 24 25 26 27 28 29 30 |
# File 'lib/extensions/memcache.rb', line 18 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
39 40 41 |
# File 'lib/extensions/memcache.rb', line 39 def has_lock? key @locks[key].present? end |
#lock_and_set(key, value, expiry = 0, raw = false) ⇒ Object
12 13 14 15 16 |
# File 'lib/extensions/memcache.rb', line 12 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
43 44 45 |
# File 'lib/extensions/memcache.rb', line 43 def lock_key name "LOCK-#{@name}" end |
#perform(op, key, *args) ⇒ Object
Chokepoint method for instrumentation
48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 |
# File 'lib/extensions/memcache.rb', line 48 def perform(op, key, * args) retry_count = 0 key = key.to_s validate_key(key) key = key_with_namespace(key) begin server = ring.server_for_key(key) server.request(op, key, * args) # We rescue exception here, not NetworkError rescue Exception => e retry_count += 1 sleep(MEMCACHE['retry_sleep_interval']) if retry_count < MEMCACHE['retry_count'] Dalli.logger.debug { e. } Dalli.logger.debug { "retrying request with new server" } retry else raise "An Error occurred within Dalli and Memcached" end end end |
#release_lock(key) ⇒ Object
32 33 34 35 36 37 |
# File 'lib/extensions/memcache.rb', line 32 def release_lock key if has_lock? key delete lock_key(key) @locks.delete key end end |