edge badge

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.

Methods
C
D
I
N
R
Constants
MAX_KEY_BYTESIZE = 1024
 

Keys are truncated with their own SHA2 digest if they exceed 1kB

DEFAULT_REDIS_OPTIONS = { connect_timeout: 20, read_timeout: 1, write_timeout: 1, reconnect_attempts: 0, }
 
DEFAULT_ERROR_HANDLER = -> (method:, returning:, exception:) do if logger logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.message}" } end end
 
DELETE_GLOB_LUA = "for i, name in ipairs(redis.call('KEYS', ARGV[1])) do redis.call('DEL', name); end"
 
Attributes
[R] max_key_bytesize
[R] redis_options
Class Public methods
new(namespace: nil, compress: true, compress_threshold: 1.kilobyte, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **redis_options)

Creates a new Redis cache store.

Handles three options: block provided to instantiate, single URL provided, and multiple URLs provided.

:redis Proc   -> options[:redis].call
: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: <tt>namespace: 'myapp-cache'<tt>.

Compression is enabled by default with a 1kB threshold, so cached values larger than 1kB are automatically compressed. Disable by passing cache: 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.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 162
def initialize(namespace: nil, compress: true, compress_threshold: 1.kilobyte, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **redis_options)
  @redis_options = redis_options

  @max_key_bytesize = MAX_KEY_BYTESIZE
  @error_handler = error_handler

  super namespace: namespace,
    compress: compress, compress_threshold: compress_threshold,
    expires_in: expires_in, race_condition_ttl: race_condition_ttl
end
Instance Public methods
cleanup(options = nil)

Cache Store API implementation.

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

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 252
def cleanup(options = nil)
  super
end
clear(options = nil)

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

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 260
def clear(options = nil)
  failsafe :clear do
    if namespace = merged_options(options)[namespace]
      delete_matched "*", namespace: namespace
    else
      redis.flushdb
    end
  end
end
decrement(name, amount = 1, options = nil)

Cache Store API implementation.

Decrement a cached value. This method uses the Redis decr atomic operator and can only be used on values written with the :raw option. Calling it on a value not stored with :raw will initialize that value to zero.

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 242
def decrement(name, amount = 1, options = nil)
  instrument :decrement, name, amount: amount do
    redis.decrby normalize_key(name, options), amount
  end
end
delete_matched(matcher, options = nil)

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.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 209
def delete_matched(matcher, options = nil)
  instrument :delete_matched, matcher do
    case matcher
    when String
      redis.eval DELETE_GLOB_LUA, [], [namespace_key(matcher, options)]
    else
      raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}"
    end
  end
end
increment(name, amount = 1, options = nil)

Cache Store API implementation.

Increment a cached value. This method uses the Redis incr atomic operator and can only be used on values written with the :raw option. Calling it on a value not stored with :raw will initialize that value to zero.

Failsafe: Raises errors.

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 228
def increment(name, amount = 1, options = nil)
  instrument :increment, name, amount: amount do
    redis.incrby normalize_key(name, options), amount
  end
end
inspect()
# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 177
def inspect
  instance = @redis || @redis_options
  "<##{self.class} options=#{options.inspect} redis=#{instance.inspect}>"
end
read_multi(*names)

Cache Store API implementation.

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

# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 186
def read_multi(*names)
  if mget_capable?
    read_multi_mget(*names)
  else
    super
  end
end
redis()
# File activesupport/lib/active_support/cache/redis_cache_store.rb, line 173
def redis
  @redis ||= self.class.build_redis(**redis_options)
end