2015-09-10 51 views
0

我只是想知道如何將緩慢的請求緩存到數據庫中的外部API,因爲我不想維護memcache服務,但我確實希望分佈式系統能夠在heroku上的多個dynos和worker上工作。如何使用Rails緩存API將外部API請求緩存到SQL數據庫?

我可以通過構建自己的緩存表來實現,但我想知道是否有更簡單的方法,特別是使用現有緩存語法的方法。

謝謝!

+0

爲什麼不試試Redis並用** Rails.cache.fetch {} **來包裝緩慢的查詢? – Anatoly

+0

不想設置另一臺服務器 – cjm2671

回答

2

您可以通過致電Rails.cache.fetch來緩存Rails中的任何內容。你傳遞一個緩存的查找鍵,如果緩存中存在一個值(「緩存命中」),那麼它將被用來代替緩慢的代碼。

比方說,我們有一個API,它需要兩個機場代碼和日期,並返回它可以找到的最佳價格。這可能是一個緩慢的查詢,所以它的緩存一個很好的候選人:

def find_best_price(start_airport, end_airport, date) 
    Rails.cache.fetch(cache_key_for(start_airport, end_airport, date)) do 
    AirportPriceAPI.find_best_price(start_airport, end_airport, date) 
    end 
end 

# Different routes & dates will have different prices, so we 
# need to have different cache keys for them. 
def cache_key_for(start_airport, end_airport, date) 
    "best_price:#{start_airport}:#{end_airport}:#{date}" 
end 

您可以通過setting config.cache_store配置數據存儲於緩存中config/application.rb。 Rails有幾種內置的,但並不都適用於Heroku。你不能使用FileStore,因爲dynos don't have persistent storage它不在dynos之間共享。 MemoryStore不在dynos中共享,如果您的dyno重新啓動,將會被清除。

Heroku最好的選擇是the MemCacheStore。它支持Rails的開箱即用,並且Heroku will give you 30Mb of memcache space for free。這是快速和完美的使用多個dynos之間。

但是,如果您確實想緩存數據庫中的值,則可以使用a custom cache class提供您的應用程序。您所要做的只是extend ActiveSupport::Cache::Store並確保實施read,write,exist?,deletefetch。而有人的already packaged a DB-backed cache store as a gem,所以你甚至不必自己實現低級細節。 :)

+0

你是我的英雄。謝謝! – cjm2671