简体   繁体   English

需要缓存5分钟的Rails片段

[英]Rails fragment that needs caching for 5 minutes

These are some lines I have in Rails: 我在Rails中有以下几行:

@quickbar_posts = []
SETTINGS[:news_groups].each do |group_short_name|
  @quickbar_posts << quickbar_posts(group_short_name)
end

What I would like is that variable @quickbar_posts to be cached in memory for 5 minutes OR for the final output of the function quickbar_posts (after it has exited the for-loop) to be saved locally in the filesystem for 5 minutes. 我想要的是将变量@quickbar_posts缓存在内存中5分钟,或者将函数quickbar_posts的最终输出(退出for循环后)在文件系统中本地保存5分钟。

My problem is that every time this is run, it's highly inefficient for this to be fetched every time, so I just want it saved for 5 minutes, then fetched again, invalidating the previously cached item if the age of the cached item is > 5 minutes. 我的问题是,每次运行该函数时,每次获取它的效率都非常低,所以我只希望将其保存5分钟,然后再次获取,如果缓存项目的年龄大于5,则使先前缓存的项目无效分钟。

In addition, adding or changing gems is not possible - since this code is running in production and for reasons that can't be explained here, nothing else can be changed in production. 此外,无法添加或更改gem-由于此代码正在生产中运行,并且由于此处无法解释的原因,因此在生产中无其他更改。

ActiveSupport part of Rails allows to use cache. Rails的ActiveSupport部分允许使用缓存。

You should verify that cache is enabled so in config/enviroments/production.rb you should set the following flag: 您应该验证缓存已启用,因此在config/enviroments/production.rb ,应设置以下标志:

config.action_controller.perform_caching = true

To cache @quickbar_posts for 5 minutes, you can use the following code: 要将@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)}
end

Ruby 1.8.7 syntax: Ruby 1.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

You can use different cache stores, to set the one you want, you can do it in config/application.rb on in config/environments/your_environment.rb (production/test/deploy) 您可以使用不同的缓存存储区来设置所需的缓存存储区,可以在config/environments/your_environment.rb (生产/测试/部署)的config/application.rb进行设置。

To use ActiveSupport::Cache::MemoryStore : 要使用ActiveSupport :: Cache :: MemoryStore

config.cache_store = :memory_store

To use ActiveSupport::Cache::FileStore : 要使用ActiveSupport :: Cache :: FileStore

config.cache_store = :file_store, "/path/to/cache/directory"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM