Class: Redlocker::Lock

Inherits:
Object
  • Object
show all
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

Instance Method Summary collapse

Constructor Details

#initialize(client:, name:, timeout:, delay:) ⇒ Lock

Creates a new Redlocker::Lock instance.

Parameters:

  • client (Redlocker::Client)

    The client

  • name (String)

    The name of the lock

  • timeout (Integer, Float)

    How long to wait for the lock. If the lock can not be acquired within that time, a Redlocker::TimeoutError will be raised.

  • delay (Integer, Float)

    How long to wait between subsequent checks of whether or not the lock is free. Default is 0.25 seconds.



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

#clientObject (readonly)

Returns the value of attribute client.



10
11
12
# File 'lib/redlocker/lock.rb', line 10

def client
  @client
end

#delayObject (readonly)

Returns the value of attribute delay.



10
11
12
# File 'lib/redlocker/lock.rb', line 10

def delay
  @delay
end

#nameObject (readonly)

Returns the value of attribute name.



10
11
12
# File 'lib/redlocker/lock.rb', line 10

def name
  @name
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



10
11
12
# File 'lib/redlocker/lock.rb', line 10

def timeout
  @timeout
end

#tokenObject (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.

Parameters:

  • block (Proc)

    The block which should be executed when the lock is acquired.

Raises:



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