[英]How do I get Rails to use my memory cache instead of oging to the database?
我在Mac Sierra機器(PostGres 9.5)上使用Rails 4.2.7。 我想使用內存緩存來緩存一些更常見的數據庫查詢。 例如,這是一個具有一些緩存方法的模型……
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似乎根本沒有使用我的內存緩存。
您應該在development.rb中啟用perform_caching:
config.action_controller.perform_caching = true
一旦完成。 重新啟動控制台。 觸發方法。 它將第一次從數據庫中加載,下次它將從您的內存緩存中加載。
另外,我建議您使用Shopify的identify_cache gem。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.