如何启用模型数据缓存?

Dav*_*ave 5 postgresql caching model ruby-on-rails ruby-on-rails-4

如何跨请求/操作启用缓存?

我的堆栈:

  • 轨道 4.2.7
  • Postgres 9.5

我在 Rails 日志中注意到以下内容

  Country Load (0.4ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."iso" = $1 LIMIT 1  [["iso", "US"]]
  State Load (1.4ms)  SELECT  "states".* FROM "states" WHERE "states"."iso" = $1 AND "states"."country_id" = $2 LIMIT 1  [["iso", "OH"], ["country_id", 233]]
  Country Load (0.3ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."iso" = $1 LIMIT 1  [["iso", "US"]]
  State Load (1.1ms)  SELECT  "states".* FROM "states" WHERE "states"."iso" = $1 AND "states"."country_id" = $2 LIMIT 1  [["iso", "OH"], ["country_id", 233]]
  Country Load (3.6ms)  SELECT  "countries".* FROM "countries" WHERE "countries"."iso" = $1 LIMIT 1  [["iso", "US"]]
  State Load (1.2ms)  SELECT  "states".* FROM "states" WHERE "states"."iso" = $1 AND "states"."country_id" = $2 LIMIT 1  [["iso", "OH"], ["country_id", 233]]
Run Code Online (Sandbox Code Playgroud)

请注意,相同的查询正在快速连续地对我的数据库运行多次。有什么方法可以向 Rails 表明某些表/模型不太可能更改,因此某些查找可以缓存在应用程序服务器上?

And*_*eko 5

有什么方法可以向 Rails 表明某些表/模型不太可能更改,因此某些查找可以缓存在应用程序服务器上?

当然,模型缓存似乎非常适合这里。

本文将让您对设置不同类型的缓存有一个很好的概述。

另外,请查看有关缓存的官方指南

基本上,您想要研究模型缓存。

您可以编写扩展并在要缓存的模型中使用它:

module ModelCachingExtention
  extend ActiveSupport::Concern

  included do
    class << self
      # The first time you call Model.all_cached it will cache the collection,
      # each consequent call will not fire the DB query
      def all_cached
        Rails.cache.fetch(['cached_', name.underscore.to_s, 's']) { all.load }
      end
    end

    after_commit :clear_cache

    private

    # Making sure, that data is in consistent state by removing the cache
    # everytime, the table is touched (eg some record is edited/created/destroyed etc).
    def clear_cache
      Rails.cache.delete(['cached_', self.class.name.underscore.to_s, 's'])
    end
  end
end
Run Code Online (Sandbox Code Playgroud)

然后在模型中使用它:

class Country < ActiveRecord::Base
  include ModelCachingExtention
end
Run Code Online (Sandbox Code Playgroud)

现在,在使用时,Country.all_cached您将返回带有零数据库查询的缓存集合(一旦被缓存)。