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
EXTEND_LIFE_SCRIPT =
<<-eos
  if redis.call("get", KEYS[1]) == ARGV[1] then
    redis.call("expire", KEYS[1], ARGV[2])
    return 0
  else
    return 1
  end
eos

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ RedisInstance

Returns a new instance of RedisInstance.



103
104
105
106
107
108
109
110
111
# File 'lib/redlock/client.rb', line 103

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

  load_scripts
end

Instance Method Details

#extend(resource, val, ttl) ⇒ Object



119
120
121
122
123
124
# File 'lib/redlock/client.rb', line 119

def extend(resource, val, ttl)
  recover_from_script_flush do
    rc = @redis.evalsha @extend_life_script_sha, keys: [resource], argv: [val, ttl]
    rc == 0
  end
end

#load_scriptsObject



136
137
138
139
140
# File 'lib/redlock/client.rb', line 136

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

#load_scripts_without_testingObject



28
29
30
31
32
# File 'lib/redlock/testing.rb', line 28

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

#lock(resource, val, ttl) ⇒ Object



113
114
115
116
117
# File 'lib/redlock/client.rb', line 113

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

#unlock(resource, val) ⇒ Object



126
127
128
129
130
131
132
# File 'lib/redlock/client.rb', line 126

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