Class: Redlock::Client

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

Constant Summary collapse

DEFAULT_REDIS_URLS =
['redis://localhost:6379']
DEFAULT_RETRY_COUNT =
3
DEFAULT_RETRY_DELAY =
200
CLOCK_DRIFT_FACTOR =
0.01
UNLOCK_SCRIPT =
<<-eos
  if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
  else
    return 0
  end
eos

Instance Method Summary collapse

Constructor Details

#initialize(server_urls = DEFAULT_REDIS_URLS, options = {}) ⇒ Client

Create a distributed lock manager implementing redlock algorithm. Params:

server_urls

the array of redis hosts.

options

You can override the default value for `retry_count` and `retry_delay`.

* `retry_count` being how many times it'll try to lock a resource (default: 3)
* `retry_delay` being how many ms to sleep before try to lock again (default: 200)

24
25
26
27
28
29
# File 'lib/redlock/client.rb', line 24

def initialize(server_urls=DEFAULT_REDIS_URLS, options={})
  @servers = server_urls.map {|url| Redis.new(url: url)}
  @quorum = server_urls.length / 2 + 1
  @retry_count = options[:retry_count] || DEFAULT_RETRY_COUNT
  @retry_delay = options[:retry_delay] || DEFAULT_RETRY_DELAY
end

Instance Method Details

#lock(resource, ttl, &block) ⇒ Object

Locks a resource for a given time. (in milliseconds) Params:

resource

the resource (or key) string to be locked.

ttl

The time-to-live in ms for the lock.

block

an optional block that automatically unlocks the lock.


36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/redlock/client.rb', line 36

def lock(resource, ttl, &block)
  lock_info = lock_instances(resource, ttl)

  if block_given?
    begin
      yield lock_info
      !!lock_info
    ensure
      unlock(lock_info) if lock_info
    end
  else
    lock_info
  end
end

#unlock(lock_info) ⇒ Object

Unlocks a resource. Params:

lock_info

the lock that has been acquired when you locked the resource.


54
55
56
# File 'lib/redlock/client.rb', line 54

def unlock(lock_info)
  @servers.each{|s| unlock_instance(s, lock_info[:resource], lock_info[:value])}
end