Class: Redstream::Lock Private

Inherits:
Object
  • Object
show all
Defined in:
lib/redstream/lock.rb

Overview

This class is part of a private API. You should avoid using this class if possible, as it may be removed or be changed in the future.

As the name suggests, the Redstream::Lock class implements a redis based locking mechanism. It atomically (lua script) gets/sets the lock key and updates its expire timeout, in case it currently holds the lock. Moreover, once it got the lock, it tries to keep it by updating the lock expire timeout from within a thread every 3 seconds.

Examples:

lock = Redstream::Lock.new(name: "user_stream_lock")

loop do
  got_lock = lock.acquire do
    # ...
  end

  sleep(5) unless got_lock
end

Defined Under Namespace

Classes: Signal

Instance Method Summary collapse

Constructor Details

#initialize(name:) ⇒ Lock

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Returns a new instance of Lock.



39
40
41
42
# File 'lib/redstream/lock.rb', line 39

def initialize(name:)
  @name = name
  @id = SecureRandom.hex
end

Instance Method Details

#acquire(&block) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



44
45
46
47
48
49
50
51
52
53
# File 'lib/redstream/lock.rb', line 44

def acquire(&block)
  got_lock = get_lock

  if got_lock
    keep_lock(&block)
    release_lock
  end

  got_lock
end

#wait(timeout) ⇒ Object

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.



55
56
57
58
# File 'lib/redstream/lock.rb', line 55

def wait(timeout)
  @wait_redis ||= Redstream.connection_pool.with(&:dup)
  @wait_redis.brpop("#{Redstream.lock_key_name(@name)}.notify", timeout: timeout)
end