Class: ActiveSupport::Cache::RedisCacheStore
- 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 a persistent Redis server (for example, one used as an Active Job queue). Redis 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
andwrite_multi
support for Redis mget/mset. UseRedis::Distributed
4.0.1+ for distributed mget support. -
delete_matched
support for Redis KEYS globs.
Constant Summary collapse
- 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.}" } end ActiveSupport.error_reporter&.report( exception, severity: :warning, source: "redis_cache_store.active_support", ) end
Constants inherited from Store
Store::DEFAULT_POOL_OPTIONS, Store::MAX_KEY_SIZE
Instance Attribute Summary collapse
-
#redis ⇒ Object
readonly
Returns the value of attribute redis.
Attributes inherited from Store
Class Method Summary collapse
-
.build_redis(redis: nil, url: nil, **redis_options) ⇒ Object
Factory method to create a new Redis instance.
-
.supports_cache_versioning? ⇒ Boolean
Advertise cache versioning support.
Instance Method Summary collapse
-
#cleanup(options = nil) ⇒ Object
Cache Store API implementation.
-
#clear(options = nil) ⇒ Object
Clear the entire cache on all Redis servers.
-
#decrement(name, amount = 1, options = nil) ⇒ Object
Decrement a cached integer value using the Redis decrby atomic operator.
-
#delete_matched(matcher, options = nil) ⇒ Object
Cache Store API implementation.
-
#increment(name, amount = 1, options = nil) ⇒ Object
Increment a cached integer value using the Redis incrby atomic operator.
-
#initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options) ⇒ RedisCacheStore
constructor
Creates a new Redis cache store.
- #inspect ⇒ Object
-
#read_multi(*names) ⇒ Object
Cache Store API implementation.
-
#stats ⇒ Object
Get info from redis servers.
Methods included from Strategy::LocalCache
#fetch_multi, #middleware, #with_local_cache
Methods inherited from Store
#delete, #delete_multi, #exist?, #fetch, #fetch_multi, #mute, #new_entry, #read, #read_counter, #silence!, #write, #write_counter, #write_multi
Constructor Details
#initialize(error_handler: DEFAULT_ERROR_HANDLER, **redis_options) ⇒ RedisCacheStore
Creates a new Redis cache store.
There are a few ways to provide the Redis client used by the cache:
-
The
:redis
param can be:-
A Redis instance.
-
A
ConnectionPool
instance wrapping a Redis instance. -
A block that returns a Redis instance.
-
-
The
:url
param can be:-
A string used to create a Redis instance.
-
An array of strings used to create a
Redis::Distributed
instance.
-
If the final Redis instance is not already a ConnectionPool
, it will be wrapped in one using ActiveSupport::Cache::Store::DEFAULT_POOL_OPTIONS
. These options can be overridden with the :pool
param, or the pool can be disabled with :pool: false.
Option Class Result
:redis Object -> options[:redis]
: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: 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
155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 155 def initialize(error_handler: DEFAULT_ERROR_HANDLER, **) = .extract!(*UNIVERSAL_OPTIONS) redis = [:redis] already_pool = redis.instance_of?(::ConnectionPool) || (redis.respond_to?(:wrapped_pool) && redis.wrapped_pool.instance_of?(::ConnectionPool)) if !already_pool && = self.class.send(:retrieve_pool_options, ) @redis = ::ConnectionPool.new() { self.class.build_redis(**) } else @redis = self.class.build_redis(**) end @error_handler = error_handler super() end |
Instance Attribute Details
#redis ⇒ Object (readonly)
Returns the value of attribute redis.
106 107 108 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 106 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: … }, …])
78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 78 def build_redis(redis: nil, url: nil, **) # :nodoc: urls = Array(url) if redis.is_a?(Proc) redis.call elsif redis redis elsif urls.size > 1 build_redis_distributed_client(urls: urls, **) elsif urls.empty? build_redis_client(**) else build_redis_client(url: urls.first, **) end end |
.supports_cache_versioning? ⇒ Boolean
Advertise cache versioning support.
60 61 62 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 60 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.
301 302 303 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 301 def cleanup( = 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.
309 310 311 312 313 314 315 316 317 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 309 def clear( = nil) failsafe :clear do if namespace = ()[: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
.
To read the value later, call #read_counter:
cache.decrement("baz") # => 3
cache.read_counter("baz") # 3
Failsafe: Raises errors.
286 287 288 289 290 291 292 293 294 295 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 286 def decrement(name, amount = 1, = nil) = () key = normalize_key(name, ) instrument :decrement, key, amount: amount do failsafe :decrement do change_counter(key, -amount, ) 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.
210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 210 def delete_matched(matcher, = nil) unless String === matcher raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}" end pattern = namespace_key(matcher, ) instrument :delete_matched, pattern do redis.then do |c| 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.unlink(*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
.
To read the value later, call #read_counter:
cache.increment("baz") # => 7
cache.read_counter("baz") # 7
Failsafe: Raises errors.
254 255 256 257 258 259 260 261 262 263 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 254 def increment(name, amount = 1, = nil) = () key = normalize_key(name, ) instrument :increment, key, amount: amount do failsafe :increment do change_counter(key, amount, ) end end end |
#inspect ⇒ Object
173 174 175 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 173 def inspect "#<#{self.class} 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.
181 182 183 184 185 186 187 188 189 190 191 192 193 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 181 def read_multi(*names) return {} if names.empty? = names. = () keys = names.map { |name| normalize_key(name, ) } instrument_multi(:read_multi, keys, ) do |payload| read_multi_entries(names, **).tap do |results| payload[:hits] = results.keys.map { |name| normalize_key(name, ) } end end end |
#stats ⇒ Object
Get info from redis servers.
320 321 322 |
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 320 def stats redis.then { |c| c.info } end |