如何在rails中使用多个缓存? (真的)

时间:2011-10-26 05:27:09

标签: ruby-on-rails-3 caching

我想使用2个缓存 - 内存默认值为1,内存缓存为1,尽管抽象地说它应该不重要(我认为)哪两个。

内存默认值是我想要加载小而很少更改数据的地方。我一直在使用记忆库。我从那里的数据库中保留了一堆“域数据”类型的东西,我也有一些来自外部源的小数据,我每15分钟刷新一次 - 1小时。

我最近添加了memcache,因为我现在正在提供一些更大的资产。我是如何进入这个复杂的,但这些是更大的〜千字节,数量相对较少(数百),并且可高度缓存 - 它们会发生变化,但每小时刷新一次可能太多了。这个集合可能会增长,但它会在所有主机上共享。刷新很贵。

第一组数据现在已经使用默认的内存缓存一段时间了,并且表现良好。 Memcache非常适合第二组数据。

我调整了memcache,它对第二组数据非常有用。问题在于,由于我现有的代码是“思考”它在本地内存中,我每次请求都会进行几次memcache访问,这会增加我的延迟。

所以,我想使用2个缓存。想法?

(注意:memcache在不同于我的服务器的机器上运行。即使我在本地运行它,我也有一组主机,所以它不是本地的。我还想避免需要只是让更大的机器。虽然我可能通过使内存更大并且只使用内存(数据真的不是那么大)来解决这个问题,但这并不能解决我扩展的问题,所以它只会踢罐头。)

2 个答案:

答案 0 :(得分:18)

ActiveSupport :: Cache :: MemoryStore是您想要使用的。 Rails.cache使用MemoryStore,FileStore或我的DalliStore: - )

您可以拥有ActiveSupport :: Cache :: MemoryStore的全局实例并使用它或创建一个包含此对象(清理器)的单例模式的类。将Rails.cache设置为其他缓存存储,并将此单例用于MemoryStore

以下是这门课程:

module Caching
  class MemoryCache
      include Singleton

      # create a private instance of MemoryStore
      def initialize
        @memory_store = ActiveSupport::Cache::MemoryStore.new
      end

      # this will allow our MemoryCache to be called just like Rails.cache
      # every method passed to it will be passed to our MemoryStore
      def method_missing(m, *args, &block)
        @memory_store.send(m, *args, &block)
      end
  end
end

这是如何使用它:

Caching::MemoryCache.instance.write("foo", "bar")
=> true
Caching::MemoryCache.instance.read("foo")
=> "bar"
Caching::MemoryCache.instance.clear
=> 0
Caching::MemoryCache.instance.read("foo")
=> nil
Caching::MemoryCache.instance.write("foo1", "bar1")
=> true
Caching::MemoryCache.instance.write("foo2", "bar2")
=> true
Caching::MemoryCache.instance.read_multi("foo1", "foo2")
=> {"foo1"=>"bar1", "foo2"=>"bar2"}

答案 1 :(得分:6)

在初始化程序中,您只需输入:

MyMemoryCache = ActiveSupport :: Cache :: MemoryStore.new

然后你可以像这样使用它:

MyMemoryCache.fetch('my-key', 'my-value')

等等。

请注意,如果它仅用于性能优化(并且取决于时间到期),则在测试环境中禁用它可能不是一个坏主意,如下所示:

if Rails.env.test?
  MyMemoryCache = ActiveSupport::Cache::NullStore.new
else
  MyMemoryCache = ActiveSupport::Cache::MemoryStore.new
end

Rails已经通过允许您在环境初始化程序中设置不同的值config.cache_store来提供此功能。