Class: ActiveSupport::Cache::RedisCacheStore
Relationships & Source Files | |
Super Chains via Extension / Inclusion / Inheritance | |
Class Chain:
self,
Store
|
|
Instance Chain:
self,
Strategy::LocalCache ,
Store
|
|
Inherits: |
ActiveSupport::Cache::Store
|
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. UseRedis::Distributed
4.0.1+ for distributed mget support. -
#delete_matched support for Redis KEYS globs.
Constant Summary
-
DEFAULT_ERROR_HANDLER =
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 59#=> (method:, returning:, exception:) do if logger logger.error { "RedisCacheStore: #{method} failed, returned #{returning.inspect}: #{exception.class}: #{exception.}" } end end
-
DEFAULT_REDIS_OPTIONS =
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 52{ connect_timeout: 20, read_timeout: 1, write_timeout: 1, reconnect_attempts: 0, }
-
MAX_KEY_BYTESIZE =
Keys are truncated with their own SHA2 digest if they exceed 1kB
1024
-
SCAN_BATCH_SIZE =
private
The maximum number of entries to receive per SCAN call.
1000
Store
- Inherited
Class Attribute Summary
-
.supports_cache_versioning? ⇒ Boolean
readonly
Advertise cache versioning support.
Store
- Inherited
Class Method Summary
-
.new(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.
Store
- Inherited
.new | Creates a new cache. |
Instance Attribute Summary
- #max_key_bytesize readonly
- #redis_options readonly
Store
- Inherited
#logger, #options, | |
#silence? | Alias for Store#silence. |
Instance Method Summary
-
#cleanup(options = nil)
::ActiveSupport::Cache
Store API implementation. -
#clear(options = nil)
Clear the entire cache on all Redis servers.
-
#decrement(name, amount = 1, options = nil)
::ActiveSupport::Cache
Store API implementation. -
#delete_matched(matcher, options = nil)
::ActiveSupport::Cache
Store API implementation. -
#increment(name, amount = 1, options = nil)
::ActiveSupport::Cache
Store API implementation. - #inspect
-
#read_multi(*names)
::ActiveSupport::Cache
Store API implementation. - #redis
Strategy::LocalCache
- Included
#middleware | Middleware class can be inserted as a |
#with_local_cache | Use a local cache for the duration of block. |
Store
- Inherited
#cleanup | Cleanups the cache by removing expired entries. |
#clear | Clears the entire cache. |
#decrement | Decrements an integer value in the cache. |
#delete | Deletes an entry in the cache. |
#delete_matched | Deletes all entries with keys matching the pattern. |
#delete_multi | Deletes multiple entries in the cache. |
#exist? | Returns |
#fetch | Fetches data from the cache, using the given key. |
#fetch_multi | Fetches data from the cache, using the given keys. |
#increment | Increments an integer value in the cache. |
#mute | Silences the logger within a block. |
#read | Reads data from the cache, using the given key. |
#read_multi | Reads multiple values at once from the cache. |
#silence, | |
#silence! | Silences the logger. |
#write | Writes the value to the cache, with the key. |
#write_multi |
|
#key_matcher | Adds the namespace defined in the options to a pattern designed to match keys. |
Constructor Details
.new(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 -> [:redis].call
:redis Object -> [: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 Store#fetch for more.
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 172
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
Class Attribute Details
.supports_cache_versioning? ⇒ Boolean
(readonly)
Advertise cache versioning support.
# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 70
def self.supports_cache_versioning? true end
Instance Attribute Details
#max_key_bytesize (readonly)
[ GitHub ]# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 143
attr_reader :max_key_bytesize
#redis_options (readonly)
[ GitHub ]# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 142
attr_reader :
Instance Method Details
#cleanup(options = nil)
::ActiveSupport::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 304
def cleanup( = 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 312
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)
::ActiveSupport::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 285
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)
::ActiveSupport::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 233
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)
::ActiveSupport::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 262
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
[ GitHub ]# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 197
def inspect instance = @redis || @redis_options "#<#{self.class} options=#{ .inspect} redis=#{instance.inspect}>" end
#read_multi(*names)
::ActiveSupport::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 206
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
[ GitHub ]# File 'activesupport/lib/active_support/cache/redis_cache_store.rb', line 184
def redis @redis ||= begin = self.class.send(:, ) if .any? self.class.send(:ensure_connection_pool_added!) ::ConnectionPool.new( ) { self.class.build_redis(** ) } else self.class.build_redis(** ) end end end