跳至内容 跳至搜索

Memcached 缓存存储

一种将数据存储在 Memcached 中的缓存存储实现:memcached.org

目前,这是生产网站中最流行的缓存存储。

特殊功能

  • 集群和负载平衡。可以指定多个 memcached 服务器,MemCacheStore 将在所有可用服务器之间进行负载平衡。如果某个服务器宕机,MemCacheStore 将忽略它,直到它重新启动。

MemCacheStore 实现了 Strategy::LocalCache 策略,该策略在块内实现内存缓存。

命名空间
方法
C
D
I
N
S
W

常量

ESCAPE_KEY_CHARS = /[\x00-\x20%\x7F-\xFF]/n
 
KEY_MAX_SIZE = 250
 
OVERRIDDEN_OPTIONS = UNIVERSAL_OPTIONS
 

这些选项表示此实现覆盖的行为,并且不应该允许传递到 Dalli 客户端

类公共方法

new(*addresses)

创建一个新的 MemCacheStore 对象,使用给定的 memcached 服务器地址。每个地址都是一个主机名,或一个“host_name:port”形式的主机加端口字符串。例如

ActiveSupport::Cache::MemCacheStore.new("localhost", "server-downstairs.localnetwork:8229")

如果没有提供地址,但定义了 ENV['MEMCACHE_SERVERS'],则将使用它。否则,MemCacheStore 将连接到 localhost:11211(默认 memcached 端口)。传递 Dalli::Client 实例已弃用,并且将被移除。请传递一个地址。

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 118
      def initialize(*addresses)
        addresses = addresses.flatten
        options = addresses.extract_options!
        if options.key?(:cache_nils)
          options[:skip_nil] = !options.delete(:cache_nils)
        end
        super(options)

        unless [String, Dalli::Client, NilClass].include?(addresses.first.class)
          raise ArgumentError, "First argument must be an empty array, address, or array of addresses."
        end
        if addresses.first.is_a?(Dalli::Client)
          ActiveSupport.deprecator.warn(<<~MSG)
            Initializing MemCacheStore with a Dalli::Client is deprecated and will be removed in Rails 7.2.
            Use memcached server addresses instead.
          MSG
          @data = addresses.first
        else
          @mem_cache_options = options.dup
          # The value "compress: false" prevents duplicate compression within Dalli.
          @mem_cache_options[:compress] = false
          (OVERRIDDEN_OPTIONS - %i(compress)).each { |name| @mem_cache_options.delete(name) }
          @data = self.class.build_mem_cache(*(addresses + [@mem_cache_options]))
        end
      end

supports_cache_versioning?()

宣传缓存版本控制支持。

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 38
def self.supports_cache_versioning?
  true
end

实例公共方法

clear(options = nil)

清除所有 Memcached 服务器上的整个缓存。在使用共享缓存时,应谨慎使用此方法。

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 215
def clear(options = nil)
  rescue_error_with(nil) { @data.with { |c| c.flush_all } }
end

decrement(name, amount = 1, options = nil)

使用 Memcached decr 原子操作递减缓存的整数值。返回更新后的值。

如果键未设置或已过期,则将其设置为 0。Memcached 不支持负计数器。

cache.decrement("foo") # => 0

要设置特定值,请调用 write,并传递 raw: true

cache.write("baz", 5, raw: true)
cache.decrement("baz") # => 4

递减非数字值或未通过 raw: true 写入的值将失败并返回 nil

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 204
def decrement(name, amount = 1, options = nil)
  options = merged_options(options)
  instrument(:decrement, name, amount: amount) do
    rescue_error_with nil do
      @data.with { |c| c.decr(normalize_key(name, options), amount, options[:expires_in], 0) }
    end
  end
end

increment(name, amount = 1, options = nil)

使用 Memcached incr 原子操作递增缓存的整数值。返回更新后的值。

如果键未设置或已过期,则将其设置为 amount

cache.increment("foo") # => 1
cache.increment("bar", 100) # => 100

要设置特定值,请调用 write,并传递 raw: true

cache.write("baz", 5, raw: true)
cache.increment("baz") # => 6

递增非数字值或未通过 raw: true 写入的值将失败并返回 nil

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 180
def increment(name, amount = 1, options = nil)
  options = merged_options(options)
  instrument(:increment, name, amount: amount) do
    rescue_error_with nil do
      @data.with { |c| c.incr(normalize_key(name, options), amount, options[:expires_in], amount) }
    end
  end
end

inspect()

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 144
def inspect
  instance = @data || @mem_cache_options
  "#<#{self.class} options=#{options.inspect} mem_cache=#{instance.inspect}>"
end

stats()

从 memcached 服务器获取统计信息。

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 220
def stats
  @data.with { |c| c.stats }
end

write(name, value, options = nil)

ActiveSupport::Cache::Store#write 的行为相同,但支持特定于 memcached 的其他选项。

其他选项

  • raw: true - 以原始字节的形式直接将值发送到服务器。该值必须是字符串或数字。只能对原始值使用 memcached 直接操作,如 incrementdecrement

  • unless_exist: true - 防止覆盖现有的缓存条目。

# File activesupport/lib/active_support/cache/mem_cache_store.rb, line 150