Module: Adapter::Redis

Defined in:
lib/adapter/redis.rb,
lib/adapter/redis/version.rb

Constant Summary collapse

VERSION =
"0.5.1"

Instance Method Summary collapse

Instance Method Details

#clearObject



18
19
20
# File 'lib/adapter/redis.rb', line 18

def clear
  client.flushdb
end

#delete(key) ⇒ Object



14
15
16
# File 'lib/adapter/redis.rb', line 14

def delete(key)
  read(key).tap { client.del(key_for(key)) }
end

#generate_expiration(expiration) ⇒ Object

Defaults expiration to 1



62
63
64
# File 'lib/adapter/redis.rb', line 62

def generate_expiration(expiration)
  (Time.now + (expiration || 1).to_f).to_f
end

#lock(name, options = {}, &block) ⇒ Object

Raises:

  • (LockTimeout)


24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
# File 'lib/adapter/redis.rb', line 24

def lock(name, options={}, &block)
  key           = name.to_s
  start         = Time.now
  acquired_lock = false
  expiration    = nil
  expires_in    = options.fetch(:expiration, 1)
  timeout       = options.fetch(:timeout, 5)

  while (Time.now - start) < timeout
    expiration    = generate_expiration(expires_in)
    acquired_lock = client.setnx(key, expiration)
    break if acquired_lock

    old_expiration = client.get(key).to_f

    if old_expiration < Time.now.to_f
      expiration     = generate_expiration(expires_in)
      old_expiration = client.getset(key, expiration).to_f

      if old_expiration < Time.now.to_f
        acquired_lock = true
        break
      end
    end

    sleep 0.1
  end

  raise(LockTimeout.new(name, timeout)) unless acquired_lock

  begin
    yield
  ensure
    client.del(key) if expiration > Time.now.to_f
  end
end

#read(key) ⇒ Object



6
7
8
# File 'lib/adapter/redis.rb', line 6

def read(key)
  decode(client.get(key_for(key)))
end

#write(key, value) ⇒ Object



10
11
12
# File 'lib/adapter/redis.rb', line 10

def write(key, value)
  client.set(key_for(key), encode(value))
end