Class: Redlocker::Client

Inherits:
Object
  • Object
show all
Defined in:
lib/redlocker/client.rb

Overview

The ‘Redlocker::Client` class allows to easily acquire and keep distributed locks using redis. The acquired lock gets automatically renewed every second from a thread, i.e. its 5 second expiry value gets renewed in redis every second, and it gets released when the given block finishes.

Examples:

RedlockerClient = Redlocker::Client.new(redis: Redis.new)

RedlockerClient.with_lock("some_lock", timeout: 5, delay: 1) do
  # lock acquired
end

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis:, namespace: nil) ⇒ Client

Creates a new ‘Redlocker::Client` instance.

Examples:

RedlockerClient = Redlocker::Client.new(redis: Redis.new)

Parameters:

  • redis (Redis)

    The redis connection

  • namespace (String) (defaults to: nil)

    An optional namespace to use for redis keys in addition to the default ‘redlocker:` namespace.



28
29
30
31
# File 'lib/redlocker/client.rb', line 28

def initialize(redis:, namespace: nil)
  @redis = redis
  @namespace = namespace
end

Instance Attribute Details

#namespaceObject (readonly)

Returns the value of attribute namespace.



17
18
19
# File 'lib/redlocker/client.rb', line 17

def namespace
  @namespace
end

#redisObject (readonly)

Returns the value of attribute redis.



17
18
19
# File 'lib/redlocker/client.rb', line 17

def redis
  @redis
end

Instance Method Details

#with_lock(name, timeout:, delay: 0.25, &block) ⇒ Object

Acquires the specified lock or raises a ‘Redlocker::TimeoutError` when the lock can not be acquired within the specified `timeout`. You can pass a `delay`, which specifies how long to wait between subsequent checks of 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.

Examples:

RedlockerClient.with_lock("some_lock", timeout: 5, delay: 1) do
  # lock acquired
end

Parameters:

  • name (String)

    The name of the lock. Will be used as the redis key for 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) (defaults to: 0.25)

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

  • block (Proc)

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



55
56
57
# File 'lib/redlocker/client.rb', line 55

def with_lock(name, timeout:, delay: 0.25, &block)
  Lock.new(client: self, name: name, timeout: timeout, delay: delay).acquire(&block)
end