【问题标题】:Rails Low Level cache is not cachingRails 低级缓存不缓存
【发布时间】:2018-04-04 12:04:39
【问题描述】:

我有一个名为 Event 的模型。在事件模型中,我有以下代码:

def self.all_events
    Rails.cache.fetch("events", expires_in: 2.days) do
        Event.all.to_a
    end
end

我在控制器中调用all_events 方法。如果上述方法有效,那么服务器日志应该只在第一次调用控制器代码时显示查询,并且在接下来的两天内,每次事件都应该以数组的形式存在于内存中——对吧?出于某种原因,服务器日志每次都显示数据库查询。如何使缓存工作?

【问题讨论】:

  • 你在开发环境中测试这个吗?
  • heroku 和开发。它既不适用。
  • 什么版本的 Rails?你有这个配置吗:config.cache_store = :file_store, 'tmp/cache'
  • 在开发中我有 config.cache_store = :memory_store 但在生产中没有这样的行
  • 它是 ruby​​ on rails 5

标签: ruby-on-rails ruby caching activerecord ruby-on-rails-5


【解决方案1】:

您必须在两种环境中正确配置缓存设置。

我更喜欢 Redis 用于 Heroku 上的生产环境。您可以在开发环境中使用 memory_store 或 file_store 选项。 https://elements.heroku.com/addons/heroku-redis

宝石文件

gem 'redis-rails'

config/environments/production.rb

Rails.application.configure do
  config.action_controller.perform_caching = true
  config.cache_store = :redis_store
end

config/environments/development.rb

Rails.application.configure do
  config.action_controller.perform_caching = true
  config.cache_store = :memory_store
end

您可以在此处找到更多关于 Ruby on Rails 缓存的详细信息; http://guides.rubyonrails.org/caching_with_rails.html

【讨论】:

    猜你喜欢
    • 2016-08-09
    • 2017-11-07
    • 2015-08-24
    • 2015-05-25
    • 2018-04-08
    • 2020-10-07
    • 2011-09-26
    • 2018-04-17
    • 2011-12-19
    相关资源
    最近更新 更多