class RemoteLock::Adapters::Redis

Public Instance Methods

delete(key) click to toggle source
# File lib/remote_lock/adapters/redis.rb, line 29
def delete(key)
  @connection.del(key)
end
has_key?(key) click to toggle source
# File lib/remote_lock/adapters/redis.rb, line 33
def has_key?(key)
  @connection.get(key) == uid
end
store(key, expires_in_seconds) click to toggle source
# 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