Class: Redis::Lockers::Lock

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

Overview

Single lock instance.

Instance Method Summary collapse

Constructor Details

#initialize(key, ttl:) ⇒ Lock

Create a new Lock instance.

Parameters:

  • key (#to_s)

    Resource name

  • ttl (#to_i)

    TTL in milliseconds



21
22
23
24
25
26
# File 'lib/redis/lockers/lock.rb', line 21

def initialize(key, ttl:)
  @key   = key.to_s
  @ttl   = ttl.to_i
  @drift = @ttl * 0.01 + 2
  @nonce = SecureRandom.uuid
end

Instance Method Details

#acquire(redis) ⇒ Boolean

Attempts to acquire lease.

Parameters:

  • redis (Redis)

    Redis client

Returns:

  • (Boolean)

    whenever lock was acquired or not.



32
33
34
35
36
37
38
39
40
# File 'lib/redis/lockers/lock.rb', line 32

def acquire(redis)
  deadline = timestamp + @ttl + @drift
  success  = LOCK_SCRIPT.eval(redis, {
    :keys => [@key],
    :argv => [@nonce, @ttl]
  })

  success && timestamp < deadline || false
end

#release(redis) ⇒ void

This method returns an undefined value.

Release acquired lease.

Parameters:

  • redis (Redis)

    Redis client



46
47
48
# File 'lib/redis/lockers/lock.rb', line 46

def release(redis)
  UNLOCK_SCRIPT.eval(redis, :keys => [@key], :argv => [@nonce])
end