Class: ProcessBalancer::Lock::SimpleRedis::LockHandler

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

Overview

class to wrap the lock handling and provide the “extend!” method contract

Instance Method Summary collapse

Constructor Details

#initialize(key, value, ttl) ⇒ LockHandler

Returns a new instance of LockHandler.



20
21
22
23
24
25
# File 'lib/process_balancer/lock/simple_redis.rb', line 20

def initialize(key, value, ttl)
  @key      = key
  @value    = value
  @ttl      = ttl
  @acquired = false
end

Instance Method Details

#acquire!Object



27
28
29
30
31
32
33
34
35
# File 'lib/process_balancer/lock/simple_redis.rb', line 27

def acquire!
  time_source = ProcessBalancer::Lock::SimpleRedis.time_source

  timeout_ms = 5000
  wait_time  = 0.02..0.1
  start      = time_source.call

  sleep(rand(wait_time)) while !(@acquired = try_lock) && (time_source.call - start) < timeout_ms
end

#acquired?Boolean

Returns:

  • (Boolean)


43
44
45
# File 'lib/process_balancer/lock/simple_redis.rb', line 43

def acquired?
  @acquired
end

#extend!Object



53
54
55
56
57
58
59
60
61
62
# File 'lib/process_balancer/lock/simple_redis.rb', line 53

def extend!
  ProcessBalancer.redis do |c|
    c.watch(@key)
    if c.get(@key) == @value
      c.multi do
        c.set(@key, @value, ex: @ttl)
      end
    end
  end
end

#release!Object



37
38
39
40
41
# File 'lib/process_balancer/lock/simple_redis.rb', line 37

def release!
  ProcessBalancer.redis do |c|
    c.del(@key)
  end
end

#try_lockObject



47
48
49
50
51
# File 'lib/process_balancer/lock/simple_redis.rb', line 47

def try_lock
  ProcessBalancer.redis do |c|
    c.set(@key, @value, nx: true, ex: @ttl)
  end
end