Class: EOAT::Cache::RedisCache

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

Overview

Redis cache handler. Used gem redis Default use standard connection parameters.

Examples:

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

EOAT.cache = EOAT::Cache::RedisCache.new

Set Redis as a cache storage, with connect to socket and not set key prefix

EOAT.cache = EOAT::Cache::RedisCache.new(:path => '/var/run/redis.sock', :prefix => '')

Author:

Instance Method Summary collapse

Constructor Details

#initialize(**kwargs) ⇒ RedisCache

Returns a new instance of RedisCache.

Parameters:

  • kwargs (Hash)

    the keywords arguments. If not send :prefix => value set default :prefix => 'eoat:' Allows take the connection parameters, example :host => "10.0.1.1", :port => 6380 or :path => "/tmp/redis.sock"

See Also:



17
18
19
20
21
22
# File 'lib/eoat/cache/redis_cache.rb', line 17

def initialize(**kwargs)
  require 'redis'

  @prefix = kwargs.key?(:prefix) ? kwargs.delete(:prefix) : 'eoat:'
  @backend = Redis.new(kwargs)
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



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/eoat/cache/redis_cache.rb', line 29

def get(host, uri)
  # Set key as md5 string
  key = @prefix + EOAT::Cache.md5hash(host + uri)
  yaml = @backend.get(key)
  # If the data is successfully received,
  # then restore instance from yaml string
  if yaml
    if EOAT::Cache.md5hash(yaml) == @backend.get(key + '_hash')
      return YAML::load(yaml)
    else
      @backend.del(key, key + '_hash')
    end
  else
  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



50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/eoat/cache/redis_cache.rb', line 50

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 = @prefix + EOAT::Cache.md5hash(host + uri)
    # Export result instance to yaml string.
    yaml = content.to_yaml
    # Store yaml string in Redis
    @backend.set(key, yaml)
    # Set TTL
    @backend.expire(key, expire)
    # Hash record
    @backend.set(
        key + '_hash',
        EOAT::Cache.md5hash(yaml)
    )
    @backend.expire(
        key + '_hash',
        expire
    )
  end
end