Class: ActiveSupport::Cache::RedisCacheStore

Inherits:
Store show all
Includes:
Strategy::LocalCache
Defined in:
activesupport/lib/active_support/cache/redis_cache_store.rb

Overview

Redis Cache Store

Deployment note: Take care to use a *dedicated Redis cache* rather than pointing this at your existing Redis server. It won’t cope well with mixed usage patterns and it won’t expire cache entries by default.

Redis cache server setup guide: redis.io/topics/lru-cache

  • Supports vanilla Redis, hiredis, and Redis::Distributed.

  • Supports Memcached-like sharding across Redises with Redis::Distributed.

  • Fault tolerant. If the Redis server is unavailable, no exceptions are raised. Cache fetches are all misses and writes are dropped.

  • Local cache. Hot in-memory primary cache within block/middleware scope.

  • read_multi and write_multi support for Redis mget/mset. Use Redis::Distributed 4.0.1+ for distributed mget support.

  • delete_matched support for Redis KEYS globs.

Constant Summary collapse

MAX_KEY_BYTESIZE =

Keys are truncated with the ActiveSupport digest if they exceed 1kB

1024
DEFAULT_REDIS_OPTIONS =
{
  connect_timeout:    1,
  read_timeout:       1,
  write_timeout:      1,
}
DEFAULT_ERROR_HANDLER =
-> (method:, returning:, exception:) do
  if logger
    logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" }
  end
  ActiveSupport.error_reporter&.report(
    exception,
    severity: :warning,
    source: "redis_cache_store.active_support",
  )
end

Instance Attribute Summary collapse

Attributes inherited from Store

#options, #silence

Class Method Summary collapse

Instance Method Summary collapse

Methods included from Strategy::LocalCache

#middleware, #with_local_cache

Methods inherited from Store

#delete, #delete_multi, #exist?, #fetch, #fetch_multi, #mute, #new_entry, #read, #silence!, #write, #write_multi

Constructor Details

#initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options) ⇒ RedisCacheStore

Creates a new Redis cache store.

Handles four options: :redis block, :redis instance, single :url string, and multiple :url strings.

Option  Class       Result
:redis  Proc    ->  options[:redis].call
:redis  Object  ->  options[:redis]
:url    String  ->  Redis.new(url: …)
:url    Array   ->  Redis::Distributed.new([{ url: … }, { url: … }, …])

No namespace is set by default. Provide one if the Redis cache server is shared with other apps: namespace: 'myapp-cache'.

Compression is enabled by default with a 1kB threshold, so cached values larger than 1kB are automatically compressed. Disable by passing compress: false or change the threshold by passing compress_threshold: 4.kilobytes.

No expiry is set on cache entries by default. Redis is expected to be configured with an eviction policy that automatically deletes least-recently or -frequently used keys when it reaches max memory. See redis.io/topics/lru-cache for cache server setup.

Race condition TTL is not set by default. This can be used to avoid “thundering herd” cache writes when hot cache entries are expired. See ActiveSupport::Cache::Store#fetch for more.

Setting skip_nil: true will not cache nil results:

cache.fetch('foo') { nil }
cache.fetch('bar', skip_nil: true) { nil }
cache.exist?('foo') # => true
cache.exist?('bar') # => false


145
146
147
148
149
150
151
152
153
154
155
156
157
158
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 145

def initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options)
  universal_options = redis_options.extract!(*UNIVERSAL_OPTIONS)

  if pool_options = self.class.send(:retrieve_pool_options, redis_options)
    @redis = ::ConnectionPool.new(pool_options) { self.class.build_redis(**redis_options) }
  else
    @redis = self.class.build_redis(**redis_options)
  end

  @max_key_bytesize = MAX_KEY_BYTESIZE
  @error_handler = error_handler

  super(universal_options)
end

Instance Attribute Details

#max_key_bytesizeObject (readonly)

Returns the value of attribute max_key_bytesize.



108
109
110
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 108

def max_key_bytesize
  @max_key_bytesize
end

#redisObject (readonly)

Returns the value of attribute redis.



109
110
111
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 109

def redis
  @redis
end

Class Method Details

.build_redis(redis: nil, url: nil, **redis_options) ⇒ Object

Factory method to create a new Redis instance.

Handles four options: :redis block, :redis instance, single :url string, and multiple :url strings.

Option  Class       Result
:redis  Proc    ->  options[:redis].call
:redis  Object  ->  options[:redis]
:url    String  ->  Redis.new(url: …)
:url    Array   ->  Redis::Distributed.new([{ url: … }, { url: … }, …])


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 80

def build_redis(redis: nil, url: nil, **redis_options) # :nodoc:
  urls = Array(url)

  if redis.is_a?(Proc)
    redis.call
  elsif redis
    redis
  elsif urls.size > 1
    build_redis_distributed_client(urls: urls, **redis_options)
  elsif urls.empty?
    build_redis_client(**redis_options)
  else
    build_redis_client(url: urls.first, **redis_options)
  end
end

.supports_cache_versioning?Boolean

Advertise cache versioning support.

Returns:

  • (Boolean)


62
63
64
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 62

def self.supports_cache_versioning?
  true
end

Instance Method Details

#cleanup(options = nil) ⇒ Object

Cache Store API implementation.

Removes expired entries. Handled natively by Redis least-recently-/ least-frequently-used expiry, so manual cleanup is not supported.



272
273
274
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 272

def cleanup(options = nil)
  super
end

#clear(options = nil) ⇒ Object

Clear the entire cache on all Redis servers. Safe to use on shared servers if the cache is namespaced.

Failsafe: Raises errors.



280
281
282
283
284
285
286
287
288
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 280

def clear(options = nil)
  failsafe :clear do
    if namespace = merged_options(options)[:namespace]
      delete_matched "*", namespace: namespace
    else
      redis.then { |c| c.flushdb }
    end
  end
end

#decrement(name, amount = 1, options = nil) ⇒ Object

Decrement a cached integer value using the Redis decrby atomic operator. Returns the updated value.

If the key is unset or has expired, it will be set to -amount:

cache.decrement("foo") # => -1

To set a specific value, call #write passing raw: true:

cache.write("baz", 5, raw: true)
cache.decrement("baz") # => 4

Decrementing a non-numeric value, or a value written without raw: true, will fail and return nil.

Failsafe: Raises errors.



258
259
260
261
262
263
264
265
266
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 258

def decrement(name, amount = 1, options = nil)
  instrument :decrement, name, amount: amount do
    failsafe :decrement do
      options = merged_options(options)
      key = normalize_key(name, options)
      change_counter(key, -amount, options)
    end
  end
end

#delete_matched(matcher, options = nil) ⇒ Object

Cache Store API implementation.

Supports Redis KEYS glob patterns:

h?llo matches hello, hallo and hxllo
h*llo matches hllo and heeeello
h[ae]llo matches hello and hallo, but not hillo
h[^e]llo matches hallo, hbllo, ... but not hello
h[a-b]llo matches hallo and hbllo

Use \ to escape special characters if you want to match them verbatim.

See redis.io/commands/KEYS for more.

Failsafe: Raises errors.



194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 194

def delete_matched(matcher, options = nil)
  instrument :delete_matched, matcher do
    unless String === matcher
      raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}"
    end
    redis.then do |c|
      pattern = namespace_key(matcher, options)
      cursor = "0"
      # Fetch keys in batches using SCAN to avoid blocking the Redis server.
      nodes = c.respond_to?(:nodes) ? c.nodes : [c]

      nodes.each do |node|
        begin
          cursor, keys = node.scan(cursor, match: pattern, count: SCAN_BATCH_SIZE)
          node.del(*keys) unless keys.empty?
        end until cursor == "0"
      end
    end
  end
end

#increment(name, amount = 1, options = nil) ⇒ Object

Increment a cached integer value using the Redis incrby atomic operator. Returns the updated value.

If the key is unset or has expired, it will be set to amount:

cache.increment("foo") # => 1
cache.increment("bar", 100) # => 100

To set a specific value, call #write passing raw: true:

cache.write("baz", 5, raw: true)
cache.increment("baz") # => 6

Incrementing a non-numeric value, or a value written without raw: true, will fail and return nil.

Failsafe: Raises errors.



232
233
234
235
236
237
238
239
240
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 232

def increment(name, amount = 1, options = nil)
  instrument :increment, name, amount: amount do
    failsafe :increment do
      options = merged_options(options)
      key = normalize_key(name, options)
      change_counter(key, amount, options)
    end
  end
end

#inspectObject



160
161
162
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 160

def inspect
  "#<#{self.class} options=#{options.inspect} redis=#{redis.inspect}>"
end

#read_multi(*names) ⇒ Object

Cache Store API implementation.

Read multiple values at once. Returns a hash of requested keys -> fetched values.



168
169
170
171
172
173
174
175
176
177
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 168

def read_multi(*names)
  return {} if names.empty?

  options = names.extract_options!
  instrument_multi(:read_multi, names, options) do |payload|
    read_multi_entries(names, **options).tap do |results|
      payload[:hits] = results.keys
    end
  end
end

#statsObject

Get info from redis servers.



291
292
293
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 291

def stats
  redis.then { |c| c.info }
end