Class: EOAT::Cache::MemcachedCache

Inherits:
Object
  • Object
show all
Defined in:
lib/eoat/cache/memcached_cache.rb

Overview

Memcached cache handler. Used gem memcache Default use standard connection parameters.

Examples:

Set Memcached as a cache storage, with default Memcached address and port

EOAT.cache = EOAT::Cache::MemcachedCache.new

Set Redis as a cache storage, with connect to custom server:port and not set key prefix

EOAT.cache = EOAT::Cache::MemcachedCache.new('10.0.1.1:11212', '')

Author:

Instance Method Summary collapse

Constructor Details

#initialize(server = 'localhost:11211', prefix = 'eoat') ⇒ MemcachedCache

Returns a new instance of MemcachedCache.

Parameters:

  • server (String) (defaults to: 'localhost:11211')

    the connection string <ip-address>:<port>

  • prefix (String) (defaults to: 'eoat')

    the prefix for keys



15
16
17
18
19
# File 'lib/eoat/cache/memcached_cache.rb', line 15

def initialize(server='localhost:11211', prefix='eoat')
  require 'memcache'

  @backend = Memcache.new(:server => server, :namespace => prefix, :segment_large_values => true)
end

Instance Method Details

#get(host, uri) ⇒ Object, NilClass

Get object from cache

Parameters:

  • host (String)

    the request host string

  • uri (String)

    the query string

Returns:

  • (Object, NilClass)

    the instance of result class or nil if key not does not exist



26
27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/eoat/cache/memcached_cache.rb', line 26

def get(host, uri)
  # Set key as md5 string
  key = EOAT::Cache.md5hash(host + uri)
  response = @backend.get(key)
  if response
    if EOAT::Cache.md5hash(response) == @backend.get(key + '_hash')
      return YAML::load(response)
    else
      @backend.delete(key)
      @backend.delete(key + '_hash')
    end
  end
  false
end

#save(host, uri, content) ⇒ Object

Save instance of result class.

Parameters:

  • host (String)

    the request host string

  • uri (String)

    the query string

  • content (Object)

    the result class instance



45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/eoat/cache/memcached_cache.rb', line 45

def save(host, uri, content)
  # Calculate TTL in seconds
  expire = (content.cached_until - content.request_time).to_i
  # If TTL > EOAT.max_ttl set EOAT.max_tt as expire
  expire = expire > EOAT.max_ttl ? EOAT.max_ttl : expire
  # If 0 or a negative value, it does not save.
  if expire > 0
    # Set key as md5 string
    key = EOAT::Cache.md5hash(host + uri)
    yaml = content.to_yaml
    @backend.set(
        key,
        yaml,
        :expiry => expire
    )
    @backend.set(
        key + '_hash',
        EOAT::Cache.md5hash(yaml),
        :expiry => expire
    )
  end
end