Class: RemoteLock::Adapters::Redis

Inherits:
Base
  • Object
show all
Defined in:
lib/remote_lock/adapters/redis.rb

Instance Method Summary collapse

Methods inherited from Base

#initialize, valid?

Constructor Details

This class inherits a constructor from RemoteLock::Adapters::Base

Instance Method Details

#delete(key) ⇒ Object



29
30
31
# File 'lib/remote_lock/adapters/redis.rb', line 29

def delete(key)
  @connection.del(key)
end

#has_key?(key) ⇒ Boolean

Returns:

  • (Boolean)


33
34
35
# File 'lib/remote_lock/adapters/redis.rb', line 33

def has_key?(key)
  @connection.get(key) == uid
end

#store(key, expires_in_seconds) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
# File 'lib/remote_lock/adapters/redis.rb', line 6

def store(key, expires_in_seconds)
  # The previous implementation used SETNX and EXPIRE in sequence to set the
  # lock. in case a previous client failed between SETNX and EXPIRE below,
  # the key may not expire.
  # We wrap setting the value and its expiry timestamp in a transaction.
  #
  # Caveat emptor: Redis transactions are *very* different from SQL
  # transactions.

  # cancel the next transaction if another client touches our key past
  # this point
  @connection.watch(key)

  # check if another client has the key.
  # it's important to still run a transaction to clear the watch.
  have_competition = @connection.exists(key)

  !! @connection.multi do
    break if have_competition
    @connection.setex(key, expires_in_seconds, uid)
  end
end