Class: RedisLocker::Locker

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

Direct Known Subclasses

MethodLocker, ModelLocker

Constant Summary collapse

NULL_SET_VALUE =
-420

Instance Method Summary collapse

Constructor Details

#initialize(*_args) ⇒ Locker

Returns a new instance of Locker.

Raises:

  • (Errors::KeyStringNotSet)


4
5
6
7
8
9
10
11
12
# File 'lib/redis_locker/locker.rb', line 4

def initialize(*_args)
  raise Errors::KeyStringNotSet unless @key_string.is_a?(String)

  setup_redis_set
  loop do
    @instance_hash = rand(36**8).to_s(36)
    break unless redis.sismember(@key_string, @instance_hash)
  end
end

Instance Method Details

#lockObject

Raises:

  • (NotImplementedError)


14
15
16
# File 'lib/redis_locker/locker.rb', line 14

def lock
  raise NotImplementedError, '#lock has to be implemented'
end

#lock!Object

Raises:

  • (NotImplementedError)


18
19
20
# File 'lib/redis_locker/locker.rb', line 18

def lock!
  raise NotImplementedError, '#lock! has to be implemented'
end

#locked?Boolean

Returns:

  • (Boolean)

Raises:

  • (NotImplementedError)


22
23
24
# File 'lib/redis_locker/locker.rb', line 22

def locked?
  raise NotImplementedError, '#locked? has to be implemented'
end

#unlockObject

Raises:

  • (NotImplementedError)


26
27
28
# File 'lib/redis_locker/locker.rb', line 26

def unlock
  raise NotImplementedError, '#unlock has to be implemented'
end

#with_redis_lock(strategy: RedisLocker::DEFAULT_STRATEGY, retry_count: RedisLocker::DEFAULT_RETRY_COUNT, retry_interval: RedisLocker::DEFAULT_RETRY_INTERVAL, &block) ⇒ Object



30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/redis_locker/locker.rb', line 30

def with_redis_lock(strategy: RedisLocker::DEFAULT_STRATEGY, retry_count: RedisLocker::DEFAULT_RETRY_COUNT,
                    retry_interval: RedisLocker::DEFAULT_RETRY_INTERVAL, &block)
  raise Errors::UnknownStrategy unless RedisLocker::STRATEGIES.include? strategy

  return respond_to_lock(strategy: strategy, retry_count: retry_count, retry_interval: retry_interval, &block) if locked?

  lock_result = strategy == :exception ? lock! : lock # delegates throwing exception to lock!
  return unless lock_result

  begin
    yield if block
  rescue Exception => e
    unlock
    raise e
  end
  unlock # unlock returns true if everything is ok
end