下面是我在Rails中的一些行:
@quickbar_posts = []
SETTINGS[:news_groups].each do |group_short_name|
@quickbar_posts << quickbar_posts(group_short_name)
end我想要的是在内存中缓存变量@quickbar_posts 5分钟,或者将函数quickbar_posts的最终输出(在退出for循环之后)本地保存到文件系统中5分钟。
我的问题是,每次运行时,每次都要获取它是非常低效的,所以我只希望它保存5分钟,然后再取一次,如果缓存项的时间超过5分钟,则使以前缓存的项无效。
此外,添加或更改gems是不可能的,因为这段代码在生产中运行,并且由于无法在这里解释的原因,在生产中不能更改任何其他代码。
发布于 2015-04-30 00:52:42
Rails的ActiveSupport部分允许使用缓存。
您应该验证缓存是否已启用,因此在config/enviroments/production.rb中您应该设置以下标志:
config.action_controller.perform_caching = true要缓存@quickbar_posts 5分钟,可以使用以下代码:
@quickbar_posts = Rails.cache.fetch("quickbar_posts", expires_in: 5.minutes) do
SETTINGS[:news_groups].map{|group_short_name| quickbar_posts(group_short_name)}
endRuby1.8.7语法:
@quickbar_posts = Rails.cache.fetch("quickbar_posts", :expires_in => 5.minutes) do
SETTINGS[:news_groups].map{|group_short_name| quickbar_posts(group_short_name)}
end您可以使用不同的缓存存储,要设置您想要的缓存,可以在config/application.rb on中使用config/environments/your_environment.rb (生产/测试/部署)。
使用ActiveSupport::Cache::MemoryStore
config.cache_store = :memory_store使用ActiveSupport::Cache::FileStore
config.cache_store = :file_store, "/path/to/cache/directory"https://stackoverflow.com/questions/29956626
复制相似问题