class ActiveSupport::Cache::Store
:compress_threshold
option. The default threshold is 16K.
or write
. To specify the threshold at which to compress values, set thecompress: true
in the initializer or as an option to fetch
large enough to warrant compression. To turn on compression either pass
reduce time spent sending data. Since there is overhead, values must be
Caches can also store values in a compressed format to save space and
@last_mod_time = Time.now # Invalidate the entire cache by changing namespace
cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
use application logic to invalidate keys.
is a Proc, it will be invoked when each key is evaluated so that you can
to every key. The namespace can be either a static value or a Proc. If it
for your cache entries. If a namespace is defined, it will be prefixed on
If your cache is on a shared infrastructure, you can define a namespace
Nil values can be cached.
cache.read(‘city’) == cache.read(:city) # => true
will be sorted by key so they are consistent.
elements will be delimited by slashes, and the elements within a Hash
method will be called. Hashes and Arrays can also be used as keys. The
method will be called to define the key. Otherwise, the to_param
object is specified as a key and has a cache_key
method defined, this
Keys are always translated into Strings and are case sensitive. When an
cache.read(‘city’) # => “Duckburgh”
cache.write(‘city’, “Duckburgh”)
cache.read(‘city’) # => nil
cache = ActiveSupport::Cache::MemoryStore.new
ActiveSupport::Cache::Store can store any serializable Ruby object.
methods of fetch
, write
, read
, exist?
, and delete
.
Some implementations may not support all methods beyond the basic cache
popular cache store for large production websites.
ActiveSupport::Cache::MemCacheStore. MemCacheStore is currently the most
under the ActiveSupport::Cache module, e.g.
implementations, each having its own additional features. See the classes
An abstract cache store class. There are multiple cache store
def self.instrument
def self.instrument ActiveSupport::Deprecation.warn "ActiveSupport::Cache.instrument is deprecated and will be removed in Rails 5. Instrumentation is now always on so you can safely stop using it." true end
def self.instrument=(boolean)
def self.instrument=(boolean) ActiveSupport::Deprecation.warn "ActiveSupport::Cache.instrument= is deprecated and will be removed in Rails 5. Instrumentation is now always on so you can safely stop using it." true end
def cleanup(options = nil)
Options are passed to the underlying cache implementation.
Cleanup the cache by removing expired entries.
def cleanup(options = nil) raise NotImplementedError.new("#{self.class.name} does not support cleanup") end
def clear(options = nil)
The options hash is passed to the underlying cache implementation.
affect other processes if shared cache is being used.
Clear the entire cache. Be careful with this method since it could
def clear(options = nil) raise NotImplementedError.new("#{self.class.name} does not support clear") end
def decrement(name, amount = 1, options = nil)
Options are passed to the underlying cache implementation.
Decrement an integer value in the cache.
def decrement(name, amount = 1, options = nil) raise NotImplementedError.new("#{self.class.name} does not support decrement") end
def delete(name, options = nil)
Deletes an entry in the cache. Returns +true+ if an entry is deleted.
def delete(name, options = nil) options = merged_options(options) instrument(:delete, name) do delete_entry(namespaced_key(name, options), options) end end
def delete_entry(key, options) # :nodoc:
implement this method.
Delete an entry from the cache implementation. Subclasses must
def delete_entry(key, options) # :nodoc: raise NotImplementedError.new end
def delete_matched(matcher, options = nil)
Options are passed to the underlying cache implementation.
Delete all entries with keys matching the pattern.
def delete_matched(matcher, options = nil) raise NotImplementedError.new("#{self.class.name} does not support delete_matched") end
def exist?(name, options = nil)
Returns +true+ if the cache contains an entry for the given key.
def exist?(name, options = nil) options = merged_options(options) instrument(:exist?, name) do entry = read_entry(namespaced_key(name, options), options) (entry && !entry.expired?) || false end end
def expanded_key(key) # :nodoc:
called. If the key is a Hash, then keys will be sorted alphabetically.
object responds to +cache_key+. Otherwise, +to_param+ method will be
Expand key to be a consistent string value. Invoke +cache_key+ if
def expanded_key(key) # :nodoc: return key.cache_key.to_s if key.respond_to?(:cache_key) case key when Array if key.size > 1 key = key.collect{|element| expanded_key(element)} else key = key.first end when Hash key = key.sort_by { |k,_| k.to_s }.collect{|k,v| "#{k}=#{v}"} end key.to_param end
def fetch(name, options = nil)
end
:bar
cache.fetch("foo", force: true, raw: true) do
cache = ActiveSupport::Cache::MemCacheStore.new
We can use this option with #fetch too:
option, which tells the memcached server to store all values as strings.
For example, MemCacheStore's #write method supports the +:raw+
miss. +options+ will be passed to the #read and #write calls.
Internally, #fetch calls #read_entry, and calls #write_entry on a cache
Other options will be handled by the specific cache store implementation.
# cache.fetch('foo') => "new value 1"
# sleep 10 # First thread extend the life of cache by another 10 seconds
# val_2 => "original value"
# val_1 => "new value 1"
end
end
'new value 2'
val_2 = cache.fetch('foo', race_condition_ttl: 10) do
Thread.new do
end
end
'new value 1'
sleep 1
val_1 = cache.fetch('foo', race_condition_ttl: 10) do
Thread.new do
sleep 60
val_2 = nil
val_1 = nil
cache.write('foo', 'original value')
cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute)
# Set all values to expire after one minute.
any role.
a new value is generated and :race_condition_ttl does not play
life of stale cache is extended only if it expired recently. Otherwise
regenerated after the specified number of seconds. Also note that the
If the process regenerating the entry errors out, the entry will be
The key is to keep :race_condition_ttl small.
new value. After that all the processes will start getting the new value.
meantime that first process will go ahead and will write into cache the
will continue to use slightly stale data for a just a bit longer. In the
seconds. Because of extended life of the previous cache, other processes
Yes, this process is extending the time for a stale value by another few
bump the cache expiration time by the value set in :race_condition_ttl.
avoid that case the first process to find an expired cache entry will
to read data natively and then they all will try to write to cache. To
cache expires and due to heavy load several different processes will try
a cache entry is used very frequently and is under heavy load. If a
Setting :race_condition_ttl is very useful in situations where
cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes)
the +fetch+ or +write+ method to effect just one entry.
(in which case all entries will be affected), or it can be supplied to
seconds. This value can be specified as an option to the constructor
All caches support auto-expiring content after a specified number of
Setting :expires_in will set an expiration time on the cache.
in a compressed format.
Setting :compress will store a large cache entry set by the call
cache.fetch('today', force: true) # => nil
cache.write('today', 'Monday')
Setting force: true will force a cache miss:
You may also specify additional options via the +options+ argument.
cache.fetch('city') # => "Duckburgh"
end
'Duckburgh'
cache.fetch('city') do
cache.fetch('city') # => nil
cache.fetch('today') # => "Monday"
cache.write('today', 'Monday')
return value will be returned.
block will be written to the cache under the given cache key, and that
the key and executed in the event of a cache miss. The return value of the
returned. However, if a block has been passed, that block will be passed
If there is no such data in the cache (a cache miss), then +nil+ will be
the cache with the given key, then that data is returned.
Fetches data from the cache, using the given key. If there is data in
def fetch(name, options = nil) if block_given? options = merged_options(options) key = namespaced_key(name, options) cached_entry = find_cached_entry(key, name, options) unless options[:force] entry = handle_expired_entry(cached_entry, key, options) if entry get_entry_value(entry, name, options) else save_block_result_to_cache(name, options) { |_name| yield _name } end else read(name, options) end end
def fetch_multi(*names)
# => { "bam" => "bam", "boom" => "boomboom" }
cache.fetch_multi("bim", "boom") { |key| key * 2 }
cache.write("bim", "bam")
Returns a hash with the data for each of the names. For example:
Options are passed to the underlying cache implementation.
and the result will be written to the cache and returned.
the supplied block is called for each key for which there was no data,
the cache with the given keys, then that data is returned. Otherwise,
Fetches data from the cache, using the given keys. If there is data in
def fetch_multi(*names) options = names.extract_options! options = merged_options(options) results = read_multi(*names, options) names.each_with_object({}) do |name, memo| memo[name] = results.fetch(name) do value = yield name write(name, value, options) value end end end
def find_cached_entry(key, name, options)
def find_cached_entry(key, name, options) instrument(:read, name, options) do |payload| payload[:super_operation] = :fetch if payload read_entry(key, options) end end
def get_entry_value(entry, name, options)
def get_entry_value(entry, name, options) instrument(:fetch_hit, name, options) { |payload| } entry.value end
def handle_expired_entry(entry, key, options)
def handle_expired_entry(entry, key, options) if entry && entry.expired? race_ttl = options[:race_condition_ttl].to_i if (race_ttl > 0) && (Time.now.to_f - entry.expires_at <= race_ttl) # When an entry has :race_condition_ttl defined, put the stale entry back into the cache # for a brief period while the entry is begin recalculated. entry.expires_at = Time.now + race_ttl write_entry(key, entry, :expires_in => race_ttl * 2) else delete_entry(key, options) end entry = nil end entry end
def increment(name, amount = 1, options = nil)
Options are passed to the underlying cache implementation.
Increment an integer value in the cache.
def increment(name, amount = 1, options = nil) raise NotImplementedError.new("#{self.class.name} does not support increment") end
def initialize(options = nil)
except for :namespace which can be used to set the global
Create a new cache. The options will be passed to any write method calls
def initialize(options = nil) @options = options ? options.dup : {} end
def instrument(operation, key, options = nil)
def instrument(operation, key, options = nil) log(operation, key, options) payload = { :key => key } payload.merge!(options) if options.is_a?(Hash) ActiveSupport::Notifications.instrument("cache_#{operation}.active_support", payload){ yield(payload) } end
def key_matcher(pattern, options)
this method to translate a pattern that matches names into one that
match keys. Implementations that support delete_matched should call
Add the namespace defined in the options to a pattern designed to
def key_matcher(pattern, options) prefix = options[:namespace].is_a?(Proc) ? options[:namespace].call : options[:namespace] if prefix source = pattern.source if source.start_with?('^') source = source[1, source.length] else source = ".*#{source[0, source.length]}" end Regexp.new("^#{Regexp.escape(prefix)}:#{source}", pattern.options) else pattern end end
def log(operation, key, options = nil)
def log(operation, key, options = nil) return unless logger && logger.debug? && !silence? logger.debug("Cache #{operation}: #{key}#{options.blank? ? "" : " (#{options.inspect})"}") end
def merged_options(call_options) # :nodoc:
Merge the default options with ones specific to a method call.
def merged_options(call_options) # :nodoc: if call_options options.merge(call_options) else options.dup end end
def mute
def mute previous_silence, @silence = defined?(@silence) && @silence, true yield ensure @silence = previous_silence end
def namespaced_key(key, options)
Prefix a key with the namespace. Namespace and key will be delimited
def namespaced_key(key, options) key = expanded_key(key) namespace = options[:namespace] if options prefix = namespace.is_a?(Proc) ? namespace.call : namespace key = "#{prefix}:#{key}" if prefix key end
def read(name, options = nil)
+nil+ is returned.
the cache with the given key, then that data is returned. Otherwise,
Fetches data from the cache, using the given key. If there is data in
def read(name, options = nil) options = merged_options(options) key = namespaced_key(name, options) instrument(:read, name, options) do |payload| entry = read_entry(key, options) if entry if entry.expired? delete_entry(key, options) payload[:hit] = false if payload nil else payload[:hit] = true if payload entry.value end else payload[:hit] = false if payload nil end end end
def read_entry(key, options) # :nodoc:
this method.
Read an entry from the cache implementation. Subclasses must implement
def read_entry(key, options) # :nodoc: raise NotImplementedError.new end
def read_multi(*names)
Some cache implementation may optimize this method.
in the last argument.
Read multiple values at once from the cache. Options can be passed
def read_multi(*names) options = names.extract_options! options = merged_options(options) results = {} names.each do |name| key = namespaced_key(name, options) entry = read_entry(key, options) if entry if entry.expired? delete_entry(key, options) else results[name] = entry.value end end end results end
def save_block_result_to_cache(name, options)
def save_block_result_to_cache(name, options) result = instrument(:generate, name, options) do |payload| yield(name) end write(name, result, options) result end
def silence!
def silence! @silence = true self end
def write(name, value, options = nil)
Writes the value to the cache, with the key.
def write(name, value, options = nil) options = merged_options(options) instrument(:write, name, options) do entry = Entry.new(value, options) write_entry(namespaced_key(name, options), entry, options) end end
def write_entry(key, entry, options) # :nodoc:
this method.
Write an entry to the cache implementation. Subclasses must implement
def write_entry(key, entry, options) # :nodoc: raise NotImplementedError.new end