Class: Tr8n::CacheAdapters::Redis

Inherits:
Tr8n::Cache show all
Defined in:
lib/tr8n/cache_adapters/redis.rb

Instance Method Summary collapse

Methods inherited from Tr8n::Cache

#cached_by_source?, #enabled?, #info, #reset_version, #segmented?, #update_version, #upgrade_version, #version, #versioned_key, #warn

Constructor Details

#initializeRedis

Returns a new instance of Redis.



38
39
40
41
42
43
44
# File 'lib/tr8n/cache_adapters/redis.rb', line 38

def initialize
  cache_host, cache_port = Tr8n.config.cache[:host].split(':') if Tr8n.config.cache[:host]
  cache_host ||= 'localhost'
  cache_port ||= 6379

  @cache = ::Redis.new(host: cache_host, port: cache_port)
end

Instance Method Details

#cache_nameObject



46
47
48
# File 'lib/tr8n/cache_adapters/redis.rb', line 46

def cache_name
  "redis"
end

#clear(opts = {}) ⇒ Object



104
105
106
# File 'lib/tr8n/cache_adapters/redis.rb', line 104

def clear(opts = {})
  info("Cache clear has no effect")
end

#delete(key, opts = {}) ⇒ Object



88
89
90
91
92
93
94
# File 'lib/tr8n/cache_adapters/redis.rb', line 88

def delete(key, opts = {})
  info("Cache delete: #{key}")
  @cache.del(versioned_key(key, opts))
rescue Exception => ex
  warn("Failed to delete data: #{ex.message}")
  key
end

#exist?(key, opts = {}) ⇒ Boolean

Returns:

  • (Boolean)


96
97
98
99
100
101
102
# File 'lib/tr8n/cache_adapters/redis.rb', line 96

def exist?(key, opts = {})
  data = @cache.exist(versioned_key(key, opts))
  not data.nil?
rescue Exception => ex
  warn("Failed to check if key exists: #{ex.message}")
  false
end

#fetch(key, opts = {}) ⇒ Object



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
# File 'lib/tr8n/cache_adapters/redis.rb', line 54

def fetch(key, opts = {})
  data = @cache.get(versioned_key(key, opts))
  if data
    info("Cache hit: #{key}")
    return data
  end

  info("Cache miss: #{key}")

  return nil unless block_given?

  data = yield

  store(key, data)

  data
rescue Exception => ex
  warn("Failed to retrieve data: #{ex.message}")
  return nil unless block_given?
  yield
end

#read_only?Boolean

Returns:

  • (Boolean)


50
51
52
# File 'lib/tr8n/cache_adapters/redis.rb', line 50

def read_only?
  false
end

#store(key, data, opts = {}) ⇒ Object



76
77
78
79
80
81
82
83
84
85
86
# File 'lib/tr8n/cache_adapters/redis.rb', line 76

def store(key, data, opts = {})
  info("Cache store: #{key}")
  ttl = opts[:ttl] || Tr8n.config.cache[:timeout]
  versioned_key = versioned_key(key, opts)

  @cache.set(versioned_key, data)
  @cache.expire(versioned_key, ttl) if ttl and ttl > 0
rescue Exception => ex
  warn("Failed to store data: #{ex.message}")
  data
end