ruby-on-rails - 如何启用模型数据缓存?

标签 ruby-on-rails postgresql ruby-on-rails-4 caching model

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

我的堆栈:

  • rails 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]]

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

最佳答案

Is there some way I can indicate to Rails that certain tables/models are very unlikely to change, and so certain lookups can be cached on the app server?

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

Here's the article这将使您对设置不同类型的缓存有一个很好的了解。

另外,查看 official guides关于缓存。

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

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

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

然后在模型中使用它:

class Country < ActiveRecord::Base
  include ModelCachingExtention
end

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

关于ruby-on-rails - 如何启用模型数据缓存?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40024363/

相关文章:

ruby-on-rails - 我如何/应该为我的模型覆盖 `build` 方法?

ruby-on-rails - activerecord-import gem NoMethodError : undefined method 'import'

java - JDBC 从 ArrayList 创建ArrayOf

ruby-on-rails-4 - Net::SMTPAuthenticationError,535-5.7.8 用户名和密码不被接受

ruby-on-rails - Rails month_field 数据类型

mysql - Ruby On Rails - Rake 模式 - 最大 key 长度为 767 字节

ruby-on-rails - "scoped"查询的事件管理员过滤器

SQL Upsert 语句不适用于非索引列

django - docker-machine 容器中缺少本地文件

ruby-on-rails - 在 ruby​​ 中将散列转换为数组