Class: Emcache

Inherits:
Object
  • Object
show all
Defined in:
lib/emcache.rb,
lib/emcache/version.rb

Constant Summary collapse

STATUS_SUCCESS =
0
STATUS_NOT_EXIST =
1
STATUS_LOCKED =
2
VERSION =
"0.1.1"

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options = {}) ⇒ Emcache

Returns a new instance of Emcache.



15
16
17
18
19
20
21
22
23
# File 'lib/emcache.rb', line 15

def initialize(options = {})
  parse_option(options.dup)

  @lua = {
    get: scripts('base', 'get'),
    set: scripts('base', 'set'),
    del: scripts('base', 'del')
  }
end

Instance Attribute Details

#prefixObject (readonly)

Returns the value of attribute prefix.



9
10
11
# File 'lib/emcache.rb', line 9

def prefix
  @prefix
end

#redisObject (readonly)

Returns the value of attribute redis.



9
10
11
# File 'lib/emcache.rb', line 9

def redis
  @redis
end

#timeoutObject (readonly)

Returns the value of attribute timeout.



9
10
11
# File 'lib/emcache.rb', line 9

def timeout
  @timeout
end

#ttlObject (readonly)

Returns the value of attribute ttl.



9
10
11
# File 'lib/emcache.rb', line 9

def ttl
  @ttl
end

Instance Method Details

#call(method, keys, args) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
# File 'lib/emcache.rb', line 25

def call(method, keys, args)
  logger.debug("method: #{method} sha: #{@lua[method].sha}"\
               " key: #{keys.inspect} args: #{args.inspect}")
  redis.with do |conn|
    begin
      ret = conn.evalsha(@lua[method].sha, keys, args)
      logger.debug("method: #{method} return: #{ret}")
      ret
    rescue Redis::CommandError => ex
      logger.debug("exception: #{ex.inspect}")
      raise ex unless ex.message.start_with? 'NOSCRIPT '

      load_script(conn, method)
      retry
    end
  end
end

#del(key) ⇒ Object



58
59
60
# File 'lib/emcache.rb', line 58

def del(key)
  call :del, [key], [prefix]
end

#get(key) ⇒ Object



43
44
45
46
47
48
49
50
51
52
# File 'lib/emcache.rb', line 43

def get(key)
  status, value = call :get, [key], [prefix, block_given? ? timeout : 0]
  if block_given? && status != STATUS_SUCCESS
    lock = value
    value = yield(key)

    _set(key, lock, value) if status == STATUS_NOT_EXIST
  end
  value
end

#set(key, value) ⇒ Object



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

def set(key, value)
  _set(key, '*', value)
end