Class: Redlock::Client::RedisInstance

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

Defined Under Namespace

Modules: ConnectionPoolLike

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 and ARGV[3] == "yes") 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.



131
132
133
134
135
136
137
138
139
140
141
142
143
144
# File 'lib/redlock/client.rb', line 131

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

  load_scripts
end

Instance Method Details

#load_scriptsObject



164
165
166
167
# File 'lib/redlock/client.rb', line 164

def load_scripts
  @unlock_script_sha = @redis.with { |conn| conn.script(:load, UNLOCK_SCRIPT) }
  @lock_script_sha = @redis.with { |conn| conn.script(:load, LOCK_SCRIPT) }
end

#load_scripts_without_testingObject



38
39
40
41
# File 'lib/redlock/testing.rb', line 38

def load_scripts
  @unlock_script_sha = @redis.with { |conn| conn.script(:load, UNLOCK_SCRIPT) }
  @lock_script_sha = @redis.with { |conn| conn.script(:load, LOCK_SCRIPT) }
end

#lock(resource, val, ttl, allow_new_lock) ⇒ Object



146
147
148
149
150
151
152
# File 'lib/redlock/client.rb', line 146

def lock(resource, val, ttl, allow_new_lock)
  recover_from_script_flush do
    @redis.with { |conn| conn.evalsha @lock_script_sha, keys: [resource], argv: [val, ttl, allow_new_lock] }
  end
rescue Redis::BaseConnectionError
  false
end

#unlock(resource, val) ⇒ Object



154
155
156
157
158
159
160
# File 'lib/redlock/client.rb', line 154

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