Class: Sidekiq::Lock::RedisLock

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

Instance Method Summary collapse

Constructor Details

#initialize(options_hash, payload) ⇒ RedisLock

checks for configuration



5
6
7
8
9
10
11
12
13
14
15
16
# File 'lib/sidekiq/lock/redis_lock.rb', line 5

def initialize(options_hash, payload)
  @options = {}

  options_hash.each_key do |key|
    @options[key.to_sym] = options_hash[key]
  end

  @payload  = payload
  @acquired = false

  timeout && name
end

Instance Method Details

#acquire!Object

acquire lock using modified SET command introduced in Redis 2.6.12 this also requires redis-rb >= 3.0.5



24
25
26
27
28
29
30
31
32
# File 'lib/sidekiq/lock/redis_lock.rb', line 24

def acquire!
  @acquired ||= Sidekiq.redis do |r|
    if Sidekiq::VERSION >= '7.2'
      r.set(name, value, 'nx', 'px', timeout)
    else
      r.set(name, value, nx: true, px: timeout)
    end
  end
end

#acquired?Boolean

Returns:

  • (Boolean)


18
19
20
# File 'lib/sidekiq/lock/redis_lock.rb', line 18

def acquired?
  @acquired
end

#nameObject

Raises:

  • (ArgumentError)


43
44
45
46
47
# File 'lib/sidekiq/lock/redis_lock.rb', line 43

def name
  raise ArgumentError, 'Provide a lock name inside sidekiq_options' if options[:name].nil?

  @name ||= (options[:name].respond_to?(:call) ? options[:name].call(*payload) : options[:name])
end

#release!Object



34
35
36
37
38
39
40
41
# File 'lib/sidekiq/lock/redis_lock.rb', line 34

def release!
  # even if lock expired / was take over by another process
  # it still means from our perspective that we released it
  @acquired = false

  # https://redis.io/commands/del/#return
  release_lock == 1
end

#timeoutObject

Raises:

  • (ArgumentError)


49
50
51
52
53
# File 'lib/sidekiq/lock/redis_lock.rb', line 49

def timeout
  raise ArgumentError, 'Provide lock timeout inside sidekiq_options' if options[:timeout].nil?

  @timeout ||= (options[:timeout].respond_to?(:call) ? options[:timeout].call(*payload) : options[:timeout]).to_i
end