Class: Sidetiq::Lock::Redis
- Inherits:
-
Object
- Object
- Sidetiq::Lock::Redis
- Includes:
- Sidetiq::Logging
- Defined in:
- lib/sidetiq/lock/redis.rb
Instance Attribute Summary collapse
-
#key ⇒ Object
readonly
Returns the value of attribute key.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
Class Method Summary collapse
Instance Method Summary collapse
-
#initialize(key, timeout = Sidetiq.config.lock_expire) ⇒ Redis
constructor
A new instance of Redis.
- #lock ⇒ Object
- #meta_data ⇒ Object
- #stale? ⇒ Boolean
- #synchronize ⇒ Object
- #unlock ⇒ Object
- #unlock! ⇒ Object
Constructor Details
Instance Attribute Details
#key ⇒ Object (readonly)
Returns the value of attribute key.
6 7 8 |
# File 'lib/sidetiq/lock/redis.rb', line 6 def key @key end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
6 7 8 |
# File 'lib/sidetiq/lock/redis.rb', line 6 def timeout @timeout end |
Class Method Details
.all ⇒ Object
8 9 10 11 12 13 14 |
# File 'lib/sidetiq/lock/redis.rb', line 8 def self.all Sidekiq.redis do |redis| redis.keys("sidetiq:*:lock").map do |key| new(key) end end end |
Instance Method Details
#lock ⇒ Object
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 |
# File 'lib/sidetiq/lock/redis.rb', line 54 def lock Sidekiq.redis do |redis| acquired = false watch(redis, key) do if !redis.exists(key) acquired = !!redis.multi do |multi| = MetaData.for_new_lock(key) multi.psetex(key, timeout, .to_json) end end end acquired end end |
#meta_data ⇒ Object
48 49 50 51 52 |
# File 'lib/sidetiq/lock/redis.rb', line 48 def @meta_data ||= Sidekiq.redis do |redis| MetaData.from_json(redis.get(key)) end end |
#stale? ⇒ Boolean
38 39 40 41 42 43 44 45 46 |
# File 'lib/sidetiq/lock/redis.rb', line 38 def stale? pttl = .pttl # Consider PTTL of -1 (never set) and larger than the # configured lock_expire as invalid. Locks with timestamps # older than 1 minute are also considered stale. pttl < 0 || pttl >= Sidetiq.config.lock_expire || . < (Sidetiq.clock.gettime.to_i - 60) end |
#synchronize ⇒ Object
21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/sidetiq/lock/redis.rb', line 21 def synchronize Sidekiq.redis do |redis| acquired = lock if acquired debug "Lock: #{key}" begin yield redis ensure unlock debug "Unlock: #{key}" end end end end |
#unlock ⇒ Object
71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 |
# File 'lib/sidetiq/lock/redis.rb', line 71 def unlock Sidekiq.redis do |redis| watch(redis, key) do if .owner == Sidetiq::Lock::MetaData::OWNER redis.multi do |multi| multi.del(key) end true else false end end end end |
#unlock! ⇒ Object
87 88 89 90 91 |
# File 'lib/sidetiq/lock/redis.rb', line 87 def unlock! Sidekiq.redis do |redis| redis.del(key) end end |