Class: Redlock::Client::RedisInstance

Inherits:
Object
  • Object
show all
Defined in:
lib/redlock/client.rb,
lib/redlock/testing.rb

Constant Summary collapse

UNLOCK_SCRIPT =
<<-eos
  if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
  else
    return 0
  end
eos
LOCK_SCRIPT =
<<-eos
  if redis.call("exists", KEYS[1]) == 0 or redis.call("get", KEYS[1]) == ARGV[1] then
    return redis.call("set", KEYS[1], ARGV[1], "PX", ARGV[2])
  end
eos

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ RedisInstance

Returns a new instance of RedisInstance.



80
81
82
83
84
85
86
87
88
# File 'lib/redlock/client.rb', line 80

def initialize(connection)
  if connection.respond_to?(:client)
    @redis = connection
  else
    @redis  = Redis.new(connection)
  end

  load_scripts
end

Instance Method Details

#load_scriptsObject



102
103
104
105
# File 'lib/redlock/client.rb', line 102

def load_scripts
  @unlock_script_sha = @redis.script(:load, UNLOCK_SCRIPT)
  @lock_script_sha = @redis.script(:load, LOCK_SCRIPT)
end

#lock(resource, val, ttl) ⇒ Object



90
91
92
# File 'lib/redlock/client.rb', line 90

def lock(resource, val, ttl)
  @redis.evalsha(@lock_script_sha, keys: [resource], argv: [val, ttl])
end

#unlock(resource, val) ⇒ Object



94
95
96
97
98
# File 'lib/redlock/client.rb', line 94

def unlock(resource, val)
  @redis.evalsha(@unlock_script_sha, keys: [resource], argv: [val])
rescue
  # Nothing to do, unlocking is just a best-effort attempt.
end