Class: Rudis::Lock

Inherits:
Structure show all
Defined in:
lib/rudis/structures/lock.rb

Defined Under Namespace

Classes: LockFailed

Instance Method Summary collapse

Methods inherited from Structure

#default_options, #del, #exists?, #expire, #expire_at, #redis_type, #rename, #ttl, #type, #watch

Methods inherited from Base

#default_options, #initialize, #key, #redis

Methods inherited from Rudis

key

Constructor Details

This class inherits a constructor from Rudis::Base

Instance Method Details

#acquire(options = {}) ⇒ Object

Raises:



5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
# File 'lib/rudis/structures/lock.rb', line 5

def acquire(options={})
  options.rmerge!(
    :tries => 1,
    :sleep => 1
  )

  return set(options) unless block_given?

  1.upto options[:tries] do
    if set(options)
      return begin
        yield
      ensure
        clear
      end
    end
    sleep options[:sleep]
  end

  # oops, we couldn't get the lock
  raise LockFailed, <<-msg.squish
    Unable to acquire lock after #{options[:tries]} time(s)
  msg
  return false
end

#set(options = {}) ⇒ Object

implements the SETNX locking algorithm from code.google.com/p/redis/wiki/SetnxCommand



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
# File 'lib/rudis/structures/lock.rb', line 33

def set(options={})
  options.rmerge!(
    :timeout => 30
  )
  if redis.setnx(key, timestamp(options[:timeout]))
    return true
  else
    # check the timestamp
    old = redis.getset(key, timestamp(options[:timeout]))
    if old < timestamp
      # expired lock, we're good
      return true
    else
      # lock is not expired, put it back
      redis.set(key, old)
      return false
    end
  end
end