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
# 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)
  cache = @backend.get(key)
  # If the data is successfully received,
  # then restore instance from yaml string
  cache ? YAML::load(cache) : 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



42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
# File 'lib/eoat/cache/redis_cache.rb', line 42

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)
  end
end