Active Support 缓存存储
一个抽象缓存存储类。有多个缓存存储实现,每个实现都有自己的附加功能。请参阅 ActiveSupport::Cache
模块下的类,例如 ActiveSupport::Cache::MemCacheStore
。 MemCacheStore
目前是大型生产网站最流行的缓存存储。
某些实现可能不支持 fetch
、write
、read
、exist?
和 delete
的基本缓存方法之外的所有方法。
ActiveSupport::Cache::Store
可以存储其 coder
的 dump
和 load
方法支持的任何 Ruby 对象。
cache = ActiveSupport::Cache::MemoryStore.new
cache.read('city') # => nil
cache.write('city', "Duckburgh")
cache.read('city') # => "Duckburgh"
cache.write('not serializable', Proc.new {}) # => TypeError
键始终转换为字符串,并且区分大小写。当一个对象被指定为键并且定义了 cache_key
方法时,将调用此方法来定义键。否则,将调用 to_param
方法。哈希和数组也可以用作键。元素将以斜杠分隔,Hash
中的元素将按键排序,以便它们保持一致。
cache.read('city') == cache.read(:city) # => true
可以缓存空值。
如果您的缓存位于共享基础架构上,则可以为缓存条目定义一个命名空间。如果定义了命名空间,它将作为前缀添加到每个键上。命名空间可以是静态值或 Proc。如果它是一个 Proc,它将在评估每个键时被调用,以便您可以使用应用程序逻辑使键失效。
cache.namespace = -> { @last_mod_time } # Set the namespace to a variable
@last_mod_time = Time.now # Invalidate the entire cache by changing namespace
属性
[R] | 选项 | |
[R] | 静默 | |
[R] | 静默? |
类公共方法
new(options = nil) 链接
创建一个新的缓存。
选项
:namespace
-
设置缓存的命名空间。如果您的应用程序与其他应用程序共享缓存,此选项特别有用。
:serializer
-
用于缓存值的序列化器。必须响应
dump
和load
。默认序列化器取决于缓存格式版本(在使用
Rails
时通过config.active_support.cache_format_version
设置)。每个格式版本的默认序列化器都包含一种回退机制,可以从任何格式版本反序列化值。此行为使得在格式版本之间迁移变得容易,而无需使整个缓存失效。您还可以指定
serializer: :message_pack
以使用基于ActiveSupport::MessagePack
的预配置序列化器。:message_pack
序列化器包含相同的反序列化回退机制,允许轻松从(或向)默认序列化器迁移。:message_pack
序列化器可能会提高性能,但它需要msgpack
gem。 :compressor
-
用于序列化缓存值的压缩器。必须响应
deflate
和inflate
。默认压缩器是
Zlib
。要定义一个新的自定义压缩器,该压缩器还可以解压缩旧的缓存条目,您可以检查压缩值是否为 Zlib 的"\x78"
签名module MyCompressor def self.deflate(dumped) # compression logic... (make sure result does not start with "\x78"!) end def self.inflate(compressed) if compressed.start_with?("\x78") Zlib.inflate(compressed) else # decompression logic... end end end ActiveSupport::Cache.lookup_store(:redis_cache_store, compressor: MyCompressor)
:coder
-
用于序列化和(可选)压缩缓存条目的编码器。必须响应
dump
和load
。默认编码器组合了序列化器和压缩器,并包括一些性能优化。如果您只需要覆盖序列化器或压缩器,则应该指定
:serializer
或:compressor
选项。如果存储可以处理缓存条目,您还可以指定
coder: nil
以省略序列化器、压缩器和编码器。例如,如果您正在使用ActiveSupport::Cache::MemoryStore
并且可以保证缓存值不会发生突变,则可以指定coder: nil
以避免防止突变的开销。:coder
选项与:serializer
和:compressor
选项互斥。同时指定它们将引发ArgumentError
。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 319 def initialize(options = nil) @options = options ? validate_options(normalize_options(options)) : {} @options[:compress] = true unless @options.key?(:compress) @options[:compress_threshold] ||= DEFAULT_COMPRESS_LIMIT @coder = @options.delete(:coder) do legacy_serializer = Cache.format_version < 7.1 && !@options[:serializer] serializer = @options.delete(:serializer) || default_serializer serializer = Cache::SerializerWithFallback[serializer] if serializer.is_a?(Symbol) compressor = @options.delete(:compressor) { Zlib } Cache::Coder.new(serializer, compressor, legacy_serializer: legacy_serializer) end @coder ||= Cache::SerializerWithFallback[:passthrough] @coder_supports_compression = @coder.respond_to?(:dump_compressed) end
实例公共方法
cleanup(options = nil) 链接
通过删除过期的条目来清理缓存。
选项传递给底层缓存实现。
某些实现可能不支持此方法。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 747 def cleanup(options = nil) raise NotImplementedError.new("#{self.class.name} does not support cleanup") end
clear(options = nil) 链接
清除整个缓存。小心使用此方法,因为如果使用共享缓存,它可能会影响其他进程。
选项哈希传递给底层缓存实现。
某些实现可能不支持此方法。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 757 def clear(options = nil) raise NotImplementedError.new("#{self.class.name} does not support clear") end
decrement(name, amount = 1, options = nil) 链接
递减缓存中的整数值。
选项传递给底层缓存实现。
某些实现可能不支持此方法。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 738 def decrement(name, amount = 1, options = nil) raise NotImplementedError.new("#{self.class.name} does not support decrement") end
delete(name, options = nil) 链接
删除缓存中的条目。如果删除条目,则返回 true
,否则返回 false
。
选项传递给底层缓存实现。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 676 def delete(name, options = nil) options = merged_options(options) instrument(:delete, name) do delete_entry(normalize_key(name, options), **options) end end
delete_matched(matcher, options = nil) 链接
删除所有键与模式匹配的条目。
选项传递给底层缓存实现。
某些实现可能不支持此方法。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 720 def delete_matched(matcher, options = nil) raise NotImplementedError.new("#{self.class.name} does not support delete_matched") end
delete_multi(names, options = nil) 链接
删除缓存中的多个条目。返回已删除条目的数量。
选项传递给底层缓存实现。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 688 def delete_multi(names, options = nil) return 0 if names.empty? options = merged_options(options) names.map! { |key| normalize_key(key, options) } instrument_multi :delete_multi, names do delete_multi_entries(names, **options) end end
exist?(name, options = nil) 链接
如果缓存包含给定键的条目,则返回 true
。
选项传递给底层缓存实现。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 702 def exist?(name, options = nil) options = merged_options(options) instrument(:exist?, name) do |payload| entry = read_entry(normalize_key(name, options), **options, event: payload) (entry && !entry.expired? && !entry.mismatched?(normalize_version(name, options))) || false end end
fetch(name, options = nil, &block) 链接
使用给定的键从缓存中获取数据。如果缓存中存在具有给定键的数据,则返回该数据。
如果缓存中没有此类数据(缓存未命中),则将返回 nil
。但是,如果已传递一个块,则该块将传递键并在缓存未命中时执行。该块的返回值将以给定的缓存键写入缓存,并且将返回该返回值。
cache.write('today', 'Monday')
cache.fetch('today') # => "Monday"
cache.fetch('city') # => nil
cache.fetch('city') do
'Duckburgh'
end
cache.fetch('city') # => "Duckburgh"
选项
在内部,fetch
调用 read_entry
,并在缓存未命中时调用 write_entry
。因此,fetch
支持与 read
和 write
相同的选项。此外,fetch
支持以下选项
-
force: true
- 强制缓存“未命中”,这意味着即使缓存值存在,我们也将其视为未命中。当force
为 true 时,传递一个块是必需的,因此这始终会导致缓存写入。cache.write('today', 'Monday') cache.fetch('today', force: true) { 'Tuesday' } # => 'Tuesday' cache.fetch('today', force: true) # => ArgumentError
当您调用其他方法来询问是否应强制缓存写入时,
:force
选项非常有用。否则,仅调用write
会更清晰。 -
skip_nil: true
- 防止缓存 nil 结果cache.fetch('foo') { nil } cache.fetch('bar', skip_nil: true) { nil } cache.exist?('foo') # => true cache.exist?('bar') # => false
-
:race_condition_ttl
- 指定在生成新值时可以重复使用过期值多少秒。当缓存条目过期时,可以通过防止多个进程同时重新生成同一条目(也称为狗群效应)来防止竞争条件。当进程遇到一个在少于
:race_condition_ttl
秒前过期的缓存条目时,它会在生成新值之前将过期时间延长:race_condition_ttl
秒。在此扩展的时间窗口内,当进程生成新值时,其他进程将继续使用旧值。第一个进程写入新值后,其他进程将使用它。如果第一个进程在生成新值时出错,另一个进程可以在扩展的时间窗口经过后尝试生成一个新值。
# Set all values to expire after one minute. cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 1.minute) cache.write('foo', 'original value') val_1 = nil val_2 = nil sleep 60 Thread.new do val_1 = cache.fetch('foo', race_condition_ttl: 10.seconds) do sleep 1 'new value 1' end end Thread.new do val_2 = cache.fetch('foo', race_condition_ttl: 10.seconds) do 'new value 2' end end cache.fetch('foo') # => "original value" sleep 10 # First thread extended the life of cache by another 10 seconds cache.fetch('foo') # => "new value 1" val_1 # => "new value 1" val_2 # => "original value"
动态选项
在某些情况下,可能需要根据缓存值动态计算选项。为了支持这一点,一个 ActiveSupport::Cache::WriteOptions
实例作为第二个参数传递给该块。例如
cache.fetch("authentication-token:#{user.id}") do |key, options|
token = authenticate_to_service
options.expires_at = token.expires_at
token
end
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 452 def fetch(name, options = nil, &block) if block_given? options = merged_options(options) key = normalize_key(name, options) entry = nil unless options[:force] instrument(:read, name, options) do |payload| cached_entry = read_entry(key, **options, event: payload) entry = handle_expired_entry(cached_entry, key, options) if entry if entry.mismatched?(normalize_version(name, options)) entry = nil else begin entry.value rescue DeserializationError entry = nil end end end payload[:super_operation] = :fetch if payload payload[:hit] = !!entry if payload end end if entry get_entry_value(entry, name, options) else save_block_result_to_cache(name, options, &block) end elsif options && options[:force] raise ArgumentError, "Missing block: Calling `Cache#fetch` with `force: true` requires a block." else read(name, options) end end
fetch_multi(*names) 链接
使用给定的键从缓存中获取数据。如果缓存中存在具有给定键的数据,则返回该数据。否则,为没有数据的每个键调用提供的块,并将结果写入缓存并返回。因此,您需要传递一个返回要写入缓存的数据的块。如果您不想在未找到缓存时写入缓存,请使用 read_multi
。
返回一个哈希,其中包含每个名称的数据。例如
cache.write("bim", "bam")
cache.fetch_multi("bim", "unknown_key") do |key|
"Fallback value for key: #{key}"
end
# => { "bim" => "bam",
# "unknown_key" => "Fallback value for key: unknown_key" }
您还可以通过 options
参数指定其他选项。有关详细信息,请参阅 fetch
。其他选项传递给底层缓存实现。例如
cache.fetch_multi("fizz", expires_in: 5.seconds) do |key|
"buzz"
end
# => {"fizz"=>"buzz"}
cache.read("fizz")
# => "buzz"
sleep(6)
cache.read("fizz")
# => nil
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 601 def fetch_multi(*names) raise ArgumentError, "Missing block: `Cache#fetch_multi` requires a block." unless block_given? return {} if names.empty? options = names.extract_options! options = merged_options(options) instrument_multi :read_multi, names, options do |payload| if options[:force] reads = {} else reads = read_multi_entries(names, **options) end writes = {} ordered = names.index_with do |name| reads.fetch(name) { writes[name] = yield(name) } end writes.compact! if options[:skip_nil] payload[:hits] = reads.keys payload[:super_operation] = :fetch_multi write_multi(writes, options) ordered end end
increment(name, amount = 1, options = nil) 链接
增加缓存中的整数值。
选项传递给底层缓存实现。
某些实现可能不支持此方法。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 729 def increment(name, amount = 1, options = nil) raise NotImplementedError.new("#{self.class.name} does not support increment") end
mute() 链接
在块内使记录器静音。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 346 def mute previous_silence, @silence = defined?(@silence) && @silence, true yield ensure @silence = previous_silence end
read(name, options = nil) 链接
使用给定的键从缓存中读取数据。如果缓存中存在具有给定键的数据,则返回该数据。否则,返回 nil
。
请注意,如果数据是用 :expires_in
或 :version
选项写入的,则在返回数据之前会应用这两个条件。
选项
-
:namespace
- 替换此调用的存储名称空间。 -
:version
- 为缓存条目指定一个版本。如果缓存的版本与请求的版本不匹配,则读取将被视为缓存未命中。此功能用于支持可回收的缓存键。
其他选项将由特定的缓存存储实现处理。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 506 def read(name, options = nil) options = merged_options(options) key = normalize_key(name, options) version = normalize_version(name, options) instrument(:read, name, options) do |payload| entry = read_entry(key, **options, event: payload) if entry if entry.expired? delete_entry(key, **options) payload[:hit] = false if payload nil elsif entry.mismatched?(version) payload[:hit] = false if payload nil else payload[:hit] = true if payload begin entry.value rescue DeserializationError payload[:hit] = false nil end end else payload[:hit] = false if payload nil end end end
read_multi(*names) 链接
一次从缓存中读取多个值。选项可以在最后一个参数中传递。
某些缓存实现可能会优化此方法。
返回一个哈希,将提供的名称映射到找到的值。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 544 def read_multi(*names) return {} if names.empty? options = names.extract_options! options = merged_options(options) instrument_multi :read_multi, names, options do |payload| read_multi_entries(names, **options, event: payload).tap do |results| payload[:hits] = results.keys end end end
silence!() 链接
使记录器静默。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 340 def silence! @silence = true self end
write(name, value, options = nil) 链接
使用键将值写入缓存。该值必须受 coder
的 dump
和 load
方法支持。
默认情况下,大于 1kB 的缓存条目会被压缩。压缩允许在相同的内存占用空间中存储更多数据,从而减少缓存驱逐并提高命中率。
选项
-
compress: false
- 禁用缓存条目的压缩。 -
:compress_threshold
- 压缩阈值,以字节为单位。大于此阈值的缓存条目将被压缩。默认为1.kilobyte
。 -
:expires_in
- 为缓存条目设置相对过期时间,以秒为单位。:expire_in
和:expired_in
是:expires_in
的别名。cache = ActiveSupport::Cache::MemoryStore.new(expires_in: 5.minutes) cache.write(key, value, expires_in: 1.minute) # Set a lower value for one entry
-
:expires_at
- 为缓存条目设置绝对过期时间。cache = ActiveSupport::Cache::MemoryStore.new cache.write(key, value, expires_at: Time.now.at_end_of_hour)
-
:version
- 为缓存条目指定一个版本。从缓存中读取时,如果缓存的版本与请求的版本不匹配,则读取将被视为缓存未命中。此功能用于支持可回收的缓存键。
其他选项将由特定的缓存存储实现处理。
来源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 663 def write(name, value, options = nil) options = merged_options(options) instrument(:write, name, options) do entry = Entry.new(value, **options.merge(version: normalize_version(name, options))) write_entry(normalize_key(name, options), entry, **options) end end
write_multi(哈希, 选项 = 无) 链接
Cache
存储 API,一次写入多个值。
源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 558 def write_multi(hash, options = nil) return hash if hash.empty? options = merged_options(options) instrument_multi :write_multi, hash, options do |payload| entries = hash.each_with_object({}) do |(name, value), memo| memo[normalize_key(name, options)] = Entry.new(value, **options.merge(version: normalize_version(name, options))) end write_multi_entries entries, **options end end
实例私有方法
key_matcher(模式, 选项) 链接
将选项中定义的命名空间添加到旨在匹配键的模式中。支持 delete_matched
的实现应调用此方法,以将匹配名称的模式转换为匹配命名空间键的模式。
源:显示 | 在 GitHub 上
# File activesupport/lib/active_support/cache.rb, line 785 def key_matcher(pattern, options) # :doc: 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