Module: Legion::Cache::Redis

Extended by:
Redis, Logging::Helper
Includes:
Pool
Included in:
Redis
Defined in:
lib/legion/cache/redis.rb

Constant Summary collapse

SERIALIZE_STRING =
"S\x00".b.freeze
SERIALIZE_JSON =
"J\x00".b.freeze

Instance Method Summary collapse

Methods included from Pool

#available, #close, #connected?, #pool_size, #restart, #size, #timeout

Instance Method Details

#build_redis_client(server: nil, servers: [], cluster: nil, replica: false, fixed_hostname: nil, username: nil, password: nil, db: nil, reconnect_attempts: [0, 0.5, 1]) ⇒ Object

rubocop:disable Metrics/ParameterLists



55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/legion/cache/redis.rb', line 55

def build_redis_client(server: nil, servers: [], cluster: nil, replica: false, fixed_hostname: nil, # rubocop:disable Metrics/ParameterLists
                       username: nil, password: nil, db: nil, reconnect_attempts: [0, 0.5, 1])
  nodes = Array(cluster).compact
  if nodes.any?
    opts = { cluster: nodes, reconnect_attempts: reconnect_attempts, timeout: @timeout }
    opts[:replica] = true if replica
    opts[:fixed_hostname] = fixed_hostname unless fixed_hostname.nil?
    opts[:username] = username unless username.nil?
    opts[:password] = password unless password.nil?
    ::Redis.new(**opts)
  else
    resolved = Legion::Cache::Settings.resolve_servers(
      driver: 'redis', server: server, servers: servers
    )
    host, port = Legion::Cache::Settings.parse_server_address(resolved.first, default_port: 6379)
    redis_opts = { host: host, port: port.to_i, reconnect_attempts: reconnect_attempts,
                   timeout: @timeout }
    redis_opts[:username] = username unless username.nil?
    redis_opts[:password] = password unless password.nil?
    redis_opts[:db] = db unless db.nil?
    redis_opts.merge!(redis_tls_options(port: port.to_i))
    ::Redis.new(**redis_opts)
  end
end

#client(server: nil, servers: [], pool_size: nil, timeout: nil, username: nil, password: nil, logger: nil, **opts) ⇒ Object

rubocop:disable Metrics/ParameterLists



16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# File 'lib/legion/cache/redis.rb', line 16

def client(server: nil, servers: [], pool_size: nil, timeout: nil, # rubocop:disable Metrics/ParameterLists
           username: nil, password: nil, logger: nil, **opts)
  return @client unless @client.nil?

  settings = defined?(Legion::Settings) ? Legion::Settings[:cache] : {}
  pool_size ||= settings[:pool_size] || 10
  timeout ||= settings[:timeout] || 5

  cluster = opts.delete(:cluster)
  replica = opts.delete(:replica) || false
  fixed_hostname = opts.delete(:fixed_hostname)
  db = opts.delete(:db)
  reconnect_attempts = opts.delete(:reconnect_attempts) || [0, 0.5, 1]

  @pool_size = pool_size
  @timeout   = timeout
  @cluster_mode = Array(cluster).compact.any?
  @component_logger = logger || log

  @connection_opts = { username: username, password: password, timeout: @timeout }.compact
  @connection_opts.merge!(redis_tls_options(port: resolve_primary_port(server: server, servers: servers, cluster: cluster)))

  checkout_timeout = opts[:pool_checkout_timeout] || settings[:pool_checkout_timeout] || @timeout
  @client = ConnectionPool.new(size: pool_size, timeout: checkout_timeout) do
    build_redis_client(server: server, servers: servers, cluster: cluster,
                       replica: replica, fixed_hostname: fixed_hostname,
                       username: username, password: password, db: db,
                       reconnect_attempts: reconnect_attempts)
  end
  @connected = true
  log.info "Redis connected to #{resolved_redis_address(server: server, servers: servers, cluster: cluster)}"
  @client
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :redis_client,
                      server: server, servers: Array(servers), cluster_nodes: Array(cluster))
  @connected = false
  raise
end

#cluster_mode?Boolean

Returns:

  • (Boolean)


80
81
82
# File 'lib/legion/cache/redis.rb', line 80

def cluster_mode?
  @cluster_mode == true
end

#delete(key) ⇒ Object



131
132
133
# File 'lib/legion/cache/redis.rb', line 131

def delete(key, **)
  delete_sync(key)
end

#delete_sync(key) ⇒ Object



135
136
137
138
139
140
141
142
# File 'lib/legion/cache/redis.rb', line 135

def delete_sync(key)
  result = client.with { |conn| conn.del(key) == 1 }
  log.debug { "[cache] DELETE #{key} success=#{result}" }
  result
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :redis_delete_sync, key: key)
  raise
end

#fetch(key, ttl: nil) ⇒ Object



94
95
96
97
98
99
100
101
# File 'lib/legion/cache/redis.rb', line 94

def fetch(key, ttl: nil)
  result = get(key)
  return result unless result.nil? && block_given?

  result = yield
  set(key, result, ttl: ttl)
  result
end

#flushObject



144
145
146
147
148
149
150
151
152
153
154
155
156
157
# File 'lib/legion/cache/redis.rb', line 144

def flush
  result = client.with do |conn|
    if cluster_mode?
      cluster_flush(conn)
    else
      conn.flushdb == 'OK'
    end
  end
  log.debug { '[cache] FLUSH completed' }
  result
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: :redis_flush)
  nil
end

#get(key) ⇒ Object



84
85
86
87
88
89
90
91
92
# File 'lib/legion/cache/redis.rb', line 84

def get(key)
  raw = client.with { |conn| conn.get(key) }
  result = deserialize_value(raw)
  log.debug { "[cache] GET #{key} hit=#{!result.nil?}" }
  result
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: :redis_get, key: key)
  nil
end

#mget(*keys) ⇒ Object



159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
# File 'lib/legion/cache/redis.rb', line 159

def mget(*keys)
  keys = keys.flatten
  return {} if keys.empty?

  result = client.with do |conn|
    if cluster_mode?
      cluster_mget(conn, keys)
    else
      values = conn.mget(*keys)
      keys.zip(values).to_h
    end
  end
  result = result.transform_values { |v| deserialize_value(v) }
  log.debug { "[cache] MGET keys=#{keys.size}" }
  result
rescue StandardError => e
  handle_exception(e, level: :warn, handled: true, operation: :redis_mget, key_count: keys.size)
  {}
end

#mset(hash, ttl: nil) ⇒ Object



179
180
181
# File 'lib/legion/cache/redis.rb', line 179

def mset(hash, ttl: nil, **)
  mset_sync(hash, ttl: ttl)
end

#mset_sync(hash, ttl: nil) ⇒ Object



183
184
185
186
187
188
189
190
191
# File 'lib/legion/cache/redis.rb', line 183

def mset_sync(hash, ttl: nil, **)
  return true if hash.empty?

  hash.each { |key, value| set_sync(key, value, ttl: ttl) }
  true
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :redis_mset_sync, key_count: hash.size)
  raise
end

#set(key, value, ttl: nil) ⇒ Object



114
115
116
# File 'lib/legion/cache/redis.rb', line 114

def set(key, value, ttl: nil, **)
  set_sync(key, value, ttl: ttl, **)
end

#set_nx(key, value, ttl: nil) ⇒ Object



103
104
105
106
107
108
109
110
111
112
# File 'lib/legion/cache/redis.rb', line 103

def set_nx(key, value, ttl: nil)
  effective_ttl = ttl || default_ttl
  serialized = serialize_value(value)
  result = client.with { |conn| conn.set(key, serialized, nx: true, ex: effective_ttl) == 'OK' }
  log.debug { "[cache] SET_NX #{key} ttl=#{effective_ttl.inspect} result=#{result}" }
  result
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :redis_set_nx, key: key, ttl: effective_ttl)
  raise
end

#set_sync(key, value, ttl: nil) ⇒ Object



118
119
120
121
122
123
124
125
126
127
128
129
# File 'lib/legion/cache/redis.rb', line 118

def set_sync(key, value, ttl: nil, **)
  effective_ttl = ttl || default_ttl
  args = {}
  args[:ex] = effective_ttl unless effective_ttl.nil?
  serialized = serialize_value(value)
  result = client.with { |conn| conn.set(key, serialized, **args) == 'OK' }
  log.debug { "[cache] SET #{key} ttl=#{effective_ttl.inspect} success=#{result}" }
  result
rescue StandardError => e
  handle_exception(e, level: :error, handled: false, operation: :redis_set_sync, key: key, ttl: effective_ttl)
  raise
end