Class: ActiveSupport::Cache::RedisCacheStore
- Includes:
- Strategy::LocalCache
- Defined in:
- 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
andwrite_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: 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.}" } end end
Instance Attribute Summary collapse
-
#max_key_bytesize ⇒ Object
readonly
Returns the value of attribute max_key_bytesize.
-
#redis_options ⇒ Object
readonly
Returns the value of attribute redis_options.
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
Cache Store API implementation.
-
#delete_matched(matcher, options = nil) ⇒ Object
Cache Store API implementation.
-
#increment(name, amount = 1, options = nil) ⇒ Object
Cache Store API implementation.
-
#initialize(namespace: nil, compress: true, compress_threshold: 1.kilobyte, coder: default_coder, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **redis_options) ⇒ RedisCacheStore
constructor
Creates a new Redis cache store.
- #inspect ⇒ Object
-
#mget_capable? ⇒ Boolean
:nodoc:.
-
#mset_capable? ⇒ Boolean
:nodoc:.
-
#read_multi(*names) ⇒ Object
Cache Store API implementation.
- #redis ⇒ Object
-
#stats ⇒ Object
Get info from redis servers.
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(namespace: nil, compress: true, compress_threshold: 1.kilobyte, coder: default_coder, expires_in: nil, race_condition_ttl: nil, 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.
143 144 145 146 147 148 149 150 151 152 153 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 143 def initialize(namespace: nil, compress: true, compress_threshold: 1.kilobyte, coder: default_coder, expires_in: nil, race_condition_ttl: nil, error_handler: DEFAULT_ERROR_HANDLER, **) @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, coder: coder end |
Instance Attribute Details
#max_key_bytesize ⇒ Object (readonly)
Returns the value of attribute max_key_bytesize.
114 115 116 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 114 def max_key_bytesize @max_key_bytesize end |
#redis_options ⇒ Object (readonly)
Returns the value of attribute redis_options.
113 114 115 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 113 def @redis_options 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: … }, …])
87 88 89 90 91 92 93 94 95 96 97 98 99 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 87 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, ** else build_redis_client url: urls.first, ** end end |
.supports_cache_versioning? ⇒ Boolean
Advertise cache versioning support.
69 70 71 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 69 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.
275 276 277 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 275 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.
283 284 285 286 287 288 289 290 291 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 283 def clear( = nil) failsafe :clear do if namespace = ()[:namespace] delete_matched "*", namespace: namespace else redis.with { |c| c.flushdb } end end end |
#decrement(name, amount = 1, options = nil) ⇒ Object
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.
256 257 258 259 260 261 262 263 264 265 266 267 268 269 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 256 def decrement(name, amount = 1, = nil) instrument :decrement, name, amount: amount do failsafe :decrement do = () key = normalize_key(name, ) redis.with do |c| c.decrby(key, amount).tap do write_key_expiry(c, key, ) end end 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.
204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 204 def delete_matched(matcher, = nil) instrument :delete_matched, matcher do unless String === matcher raise ArgumentError, "Only Redis glob strings are supported: #{matcher.inspect}" end redis.with do |c| pattern = namespace_key(matcher, ) 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
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.
233 234 235 236 237 238 239 240 241 242 243 244 245 246 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 233 def increment(name, amount = 1, = nil) instrument :increment, name, amount: amount do failsafe :increment do = () key = normalize_key(name, ) redis.with do |c| c.incrby(key, amount).tap do write_key_expiry(c, key, ) end end end end end |
#inspect ⇒ Object
168 169 170 171 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 168 def inspect instance = @redis || @redis_options "#<#{self.class} options=#{.inspect} redis=#{instance.inspect}>" end |
#mget_capable? ⇒ Boolean
:nodoc:
298 299 300 301 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 298 def mget_capable? # :nodoc: set_redis_capabilities unless defined? @mget_capable @mget_capable end |
#mset_capable? ⇒ Boolean
:nodoc:
303 304 305 306 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 303 def mset_capable? # :nodoc: set_redis_capabilities unless defined? @mset_capable @mset_capable end |
#read_multi(*names) ⇒ Object
Cache Store API implementation.
Read multiple values at once. Returns a hash of requested keys -> fetched values.
177 178 179 180 181 182 183 184 185 186 187 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 177 def read_multi(*names) if mget_capable? instrument(:read_multi, names, ) do |payload| read_multi_mget(*names).tap do |results| payload[:hits] = results.keys end end else super end end |
#redis ⇒ Object
155 156 157 158 159 160 161 162 163 164 165 166 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 155 def redis @redis ||= begin = self.class.send(:retrieve_pool_options, ) if .any? self.class.send(:ensure_connection_pool_added!) ::ConnectionPool.new() { self.class.build_redis(**) } else self.class.build_redis(**) end end end |
#stats ⇒ Object
Get info from redis servers.
294 295 296 |
# File 'lib/active_support/cache/redis_cache_store.rb', line 294 def stats redis.with { |c| c.info } end |