Class: Redlocker::Lock
- Inherits:
-
Object
- Object
- Redlocker::Lock
- Defined in:
- lib/redlocker/lock.rb
Overview
The ‘Redlocker::Lock` class allows to easily acquire and keep distributed locks using redis. The acquired lock gets automatically renewed every second, i.e. its 5 second expiry value gets renewed in redis every second, and it gets released when the given block finishes.
Instance Attribute Summary collapse
-
#client ⇒ Object
readonly
Returns the value of attribute client.
-
#delay ⇒ Object
readonly
Returns the value of attribute delay.
-
#name ⇒ Object
readonly
Returns the value of attribute name.
-
#timeout ⇒ Object
readonly
Returns the value of attribute timeout.
-
#token ⇒ Object
readonly
Returns the value of attribute token.
Instance Method Summary collapse
-
#acquire(&block) ⇒ Object
Acquires the specified lock or raises a ‘Redlocker::TimeoutError` when the lock can not be acquired within the specified `timeout`.
-
#initialize(client:, name:, timeout:, delay:) ⇒ Lock
constructor
Creates a new ‘Redlocker::Lock` instance.
Constructor Details
#initialize(client:, name:, timeout:, delay:) ⇒ Lock
Creates a new ‘Redlocker::Lock` instance.
22 23 24 25 26 27 28 |
# File 'lib/redlocker/lock.rb', line 22 def initialize(client:, name:, timeout:, delay:) @client = client @name = name @timeout = timeout @delay = delay @token = SecureRandom.hex end |
Instance Attribute Details
#client ⇒ Object (readonly)
Returns the value of attribute client.
10 11 12 |
# File 'lib/redlocker/lock.rb', line 10 def client @client end |
#delay ⇒ Object (readonly)
Returns the value of attribute delay.
10 11 12 |
# File 'lib/redlocker/lock.rb', line 10 def delay @delay end |
#name ⇒ Object (readonly)
Returns the value of attribute name.
10 11 12 |
# File 'lib/redlocker/lock.rb', line 10 def name @name end |
#timeout ⇒ Object (readonly)
Returns the value of attribute timeout.
10 11 12 |
# File 'lib/redlocker/lock.rb', line 10 def timeout @timeout end |
#token ⇒ Object (readonly)
Returns the value of attribute token.
10 11 12 |
# File 'lib/redlocker/lock.rb', line 10 def token @token end |
Instance Method Details
#acquire(&block) ⇒ Object
Acquires the specified lock or raises a ‘Redlocker::TimeoutError` when the lock can not be acquired within the specified `timeout`. Uses the specified `delay` to poll redis and check whether or not the lock is free. When the lock has been successfully acquired, it gets refreshed every second, i.e. its expiry value of 5 seconds is refreshed within redis every second.
40 41 42 43 44 45 46 47 48 |
# File 'lib/redlocker/lock.rb', line 40 def acquire(&block) raise(TimeoutError, "Did not get lock #{name} within #{timeout} seconds") unless acquire_lock begin keep_lock(&block) ensure release_lock end end |