Class: Redlock::Client::RedisInstance

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

Constant Summary collapse

UNLOCK_SCRIPT =
"  if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n    return redis.call(\"del\",KEYS[1])\n  else\n    return 0\n  end\n"
LOCK_SCRIPT =
"  if (redis.call(\"exists\", KEYS[1]) == 0 and ARGV[3] == \"yes\") or redis.call(\"get\", KEYS[1]) == ARGV[1] then\n    return redis.call(\"set\", KEYS[1], ARGV[1], \"PX\", ARGV[2])\n  end\n"

Instance Method Summary collapse

Constructor Details

#initialize(connection) ⇒ RedisInstance

Returns a new instance of RedisInstance.



115
116
117
118
119
120
121
# File 'lib/redlock/client.rb', line 115

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

Instance Method Details

#load_scriptsObject



141
142
143
144
# File 'lib/redlock/client.rb', line 141

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

#load_scripts_without_testingObject



28
29
30
31
# 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)
end

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



123
124
125
126
127
128
129
# File 'lib/redlock/client.rb', line 123

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

#unlock(resource, val) ⇒ Object



131
132
133
134
135
136
137
# File 'lib/redlock/client.rb', line 131

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