Class: EOAT::Cache::RedisCache
- Inherits:
-
Object
- Object
- EOAT::Cache::RedisCache
- Defined in:
- lib/eoat/cache/redis_cache.rb
Overview
Redis cache handler. Used gem redis
Default use standard connection parameters.
Instance Method Summary collapse
-
#get(host, uri) ⇒ Object, NilClass
Get object from cache.
-
#initialize(**kwargs) ⇒ RedisCache
constructor
A new instance of RedisCache.
-
#save(host, uri, content) ⇒ Object
Save instance of result class.
Constructor Details
#initialize(**kwargs) ⇒ RedisCache
Returns a new instance of RedisCache.
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
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.
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 |