Joh*_*gan 15 caching ruby-on-rails-3
我想使用2个缓存 - 内存默认值为1,内存缓存为1,尽管抽象地说它应该不重要(我认为)哪两个.
内存默认值是我想要加载小而很少更改数据的地方.我一直在使用记忆库.我从那里的数据库中保留了一堆"域数据"类型的东西,我也有一些来自外部源的小数据,我每15分钟刷新一次 - 1小时.
我最近添加了memcache,因为我现在正在提供一些更大的资产.我是如何进入这个复杂的,但这些是更大的〜千字节,数量相对较少(数百),并且可高度缓存 - 它们会发生变化,但每小时刷新一次可能太多了.这个集合可能会增长,但它会在所有主机上共享.刷新很昂贵.
第一组数据现在已经使用默认的内存缓存一段时间了,并且表现良好.Memcache非常适合第二组数据.
我调整了memcache,它对第二组数据非常有用.问题在于,由于我现有的代码是"思考"它是在本地内存中,我每次请求都要多次访问memcache,这会增加我的延迟.
所以,我想使用2个缓存.思考?
(注意:memcache运行在不同于我的服务器的机器上.即使我在本地运行它,我也有一组主机,所以它不是本地的.所以,我想避免需要变大虽然我可能通过使内存更大并且只使用内存来解决这个问题(数据确实不是那么大),但这并不能解决问题,因为我会扩展,所以它只会踢能够.)
Abd*_*bdo 19
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
Run Code Online (Sandbox Code Playgroud)
这是如何使用它:
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"}
Run Code Online (Sandbox Code Playgroud)
在初始化程序中,您可以放置:
MyMemoryCache = ActiveSupport :: Cache :: MemoryStore.new
然后你可以像这样使用它:
MyMemoryCache.fetch('my-key', 'my-value')
Run Code Online (Sandbox Code Playgroud)
等等.
请注意,如果它仅用于性能优化(并且取决于时间到期),则在测试环境中禁用它可能不是一个坏主意,如下所示:
if Rails.env.test?
MyMemoryCache = ActiveSupport::Cache::NullStore.new
else
MyMemoryCache = ActiveSupport::Cache::MemoryStore.new
end
Run Code Online (Sandbox Code Playgroud)
Rails已经通过允许您config.cache_store在环境初始化程序中设置不同的值来提供此功能.