如何跨请求/操作启用缓存?
我的堆栈:
- 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/