Class: Schked::RedisLocker

Inherits:
Object
  • Object
show all
Defined in:
lib/schked/redis_locker.rb

Constant Summary collapse

LOCK_KEY =
"schked:redis_locker"
LOCK_TTL =

ms

60_000

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(redis_servers, lock_ttl: LOCK_TTL, logger: Logger.new($stdout)) ⇒ RedisLocker

Returns a new instance of RedisLocker.



13
14
15
16
17
# File 'lib/schked/redis_locker.rb', line 13

def initialize(redis_servers, lock_ttl: LOCK_TTL, logger: Logger.new($stdout))
  @lock_manager = Redlock::Client.new(redis_servers, retry_count: 0)
  @lock_ttl = lock_ttl
  @logger = logger
end

Instance Attribute Details

#lock_idObject (readonly)

Returns the value of attribute lock_id.



5
6
7
# File 'lib/schked/redis_locker.rb', line 5

def lock_id
  @lock_id
end

#lock_managerObject (readonly)

Returns the value of attribute lock_manager.



5
6
7
# File 'lib/schked/redis_locker.rb', line 5

def lock_manager
  @lock_manager
end

#lock_ttlObject (readonly)

Returns the value of attribute lock_ttl.



5
6
7
# File 'lib/schked/redis_locker.rb', line 5

def lock_ttl
  @lock_ttl
end

#loggerObject (readonly)

Returns the value of attribute logger.



5
6
7
# File 'lib/schked/redis_locker.rb', line 5

def logger
  @logger
end

Instance Method Details

#extend_lockObject



33
34
35
36
37
38
39
40
41
42
# File 'lib/schked/redis_locker.rb', line 33

def extend_lock
  return false unless valid_lock?

  @lock_id = lock_manager.lock(LOCK_KEY, lock_ttl, extend: lock_id, extend_only_if_locked: true)

  !!@lock_id
rescue => e
  logger.error("Failed to extend the lock with error: #{e.message}")
  false
end

#lockObject



19
20
21
22
23
24
# File 'lib/schked/redis_locker.rb', line 19

def lock
  valid_lock? || !!try_lock
rescue => e
  logger.error("Failed to acquire a lock with error: #{e.message}")
  false
end

#unlockObject



26
27
28
29
30
31
# File 'lib/schked/redis_locker.rb', line 26

def unlock
  lock_manager.unlock(lock_id) if valid_lock?
rescue => e
  logger.error("Failed to release the lock with error: #{e.message}")
  false
end

#valid_lock?Boolean

Returns:

  • (Boolean)


44
45
46
47
48
# File 'lib/schked/redis_locker.rb', line 44

def valid_lock?
  return false unless lock_id

  lock_manager.valid_lock?(lock_id)
end