Class: Rudis::Lock
- Defined in:
- lib/rudis/structures/lock.rb
Defined Under Namespace
Classes: LockFailed
Instance Method Summary collapse
- #acquire(options = {}) ⇒ Object
-
#set(options = {}) ⇒ Object
implements the SETNX locking algorithm from code.google.com/p/redis/wiki/SetnxCommand.
Methods inherited from Structure
#default_options, #del, #exists?, #expire, #expire_at, #redis_type, #rename, #ttl, #type, #watch
Methods inherited from Base
#default_options, #initialize, #key, #redis
Methods inherited from Rudis
Constructor Details
This class inherits a constructor from Rudis::Base
Instance Method Details
#acquire(options = {}) ⇒ Object
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 |
# File 'lib/rudis/structures/lock.rb', line 5 def acquire(={}) .rmerge!( :tries => 1, :sleep => 1 ) return set() unless block_given? 1.upto [:tries] do if set() return begin yield ensure clear end end sleep [:sleep] end # oops, we couldn't get the lock raise LockFailed, <<-msg.squish Unable to acquire lock after #{[:tries]} time(s) msg return false end |
#set(options = {}) ⇒ Object
implements the SETNX locking algorithm from code.google.com/p/redis/wiki/SetnxCommand
33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/rudis/structures/lock.rb', line 33 def set(={}) .rmerge!( :timeout => 30 ) if redis.setnx(key, ([:timeout])) return true else # check the timestamp old = redis.getset(key, ([:timeout])) if old < # expired lock, we're good return true else # lock is not expired, put it back redis.set(key, old) return false end end end |