【问题标题】:How do I get Rails to use my memory cache instead of oging to the database?如何让 Rails 使用我的内存缓存而不是访问数据库?
【发布时间】:2016-12-18 19:31:52
【问题描述】:

我在我的 mac Sierra 机器上使用 Rails 4.2.7 (PostGres 9.5)。我想使用内存缓存来缓存我的一些更常见的数据库查询。例如,这是一个带有一些缓存方法的模型……

class DistanceUnit < ActiveRecord::Base

  def self.cached_find_by_id(id)
    Rails.cache.fetch("#{id}") do
      find_by_id(id)
    end
  end

  def self.cached_find_by_abbrev(abbrev)
    Rails.cache.fetch("#{abbrev}") do
      find_by_abbrev(abbrev)
    end
  end

end

我在整个应用程序中调用“cached_find_by_id”和“cached_find_by_abbrev”。然后在我的 ./config/environments/development.rb 文件中我有

  config.action_controller.perform_caching = true
  ...
  # Enable the Rails cache
  config.cache_store = :memory_store

但是当我在本地运行我的应用程序时,我注意到 SQL 查询正在运行……

  DistanceUnit Load (0.4ms)  SELECT  "distance_units".* FROM "distance_units" WHERE "distance_units"."id" = $1 LIMIT 1  [["id", 4]]

…

  DistanceUnit Load (0.3ms)  SELECT  "distance_units".* FROM "distance_units" WHERE "distance_units"."id" = $1 LIMIT 1  [["id", 4]]

我还需要做什么才能让 Rails 使用我的缓存方法? Rails 似乎根本没有使用我的内存缓存。

【问题讨论】:

    标签: ruby-on-rails ruby-on-rails-4 caching memory config


    【解决方案1】:

    您应该在 development.rb 中启用 perform_caching:

    config.action_controller.perform_caching = true
    

    一旦完成。重新启动您的控制台。触发方法。第一次从数据库加载,下一次从你的内存缓存加载。

    另外,我会推荐你​​使用 Shopify 的 identify_cache gem。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-02-06
      • 1970-01-01
      • 1970-01-01
      • 2021-07-12
      • 1970-01-01
      相关资源
      最近更新 更多