【问题标题】:Using Rails.cache in application.rb在 application.rb 中使用 Rails.cache
【发布时间】:2018-04-24 05:44:34
【问题描述】:

我正在尝试在 application.rb 中初始化我的缓存,以便在应用初始化后填充它

我的 application.rb 看起来像:

config.cache_store = :memory_store

config.after_initialize do
    Rails.cache.write('key','value)
    puts Rails.cache.read('key')
end

Rails.cache.read('key')在这里给出一个空值

但如果我将相同的代码放在 rails 的其他 ruby​​ 类中,它会给出预期的输出。

示例 my_cache.rb

    Rails.cache.write('key','value')
    puts Rails.cache.read('key') # gives output value

为了提供更多上下文,我也遇到了这种奇怪的行为,我的 Rails.cache 在 application.rb 和 my_cache.rb 中都是 ActiveSupport::Cache::NullStore,我认为应该是 ActiveSupport::Cache::MemoryStore

我正在使用 Rails 5.1.0

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    在开发环境中默认禁用缓存。

    因此我无法访问缓存。

    运行rake dev:cache 会创建一个空的caching-dev.txt,从而在开发环境中启用缓存

    这就是 development.rb 的样子

    if Rails.root.join('tmp/caching-dev.txt').exist?
      config.action_controller.perform_caching = true
      config.action_mailer.perform_caching = false
      config.cache_store = :memory_store
      config.public_file_server.headers = {
        'Cache-Control' => 'public, max-age=172800'
      }
    else
      config.action_controller.perform_caching = false
      config.action_mailer.perform_caching = false
      config.cache_store = :null_store
    end
    

    【讨论】:

      猜你喜欢
      • 2012-10-07
      • 1970-01-01
      • 2018-03-19
      • 2010-09-13
      • 1970-01-01
      • 2017-02-18
      • 1970-01-01
      • 2013-01-17
      • 2018-11-12
      相关资源
      最近更新 更多