2011-12-13 61 views
9

我正在使用我用Sinatra製作的API返回一些JSON來構建一個簡單的應用程序。這是相當多的JSON,我的應用程序的API依賴於對其他API的幾百個請求。在Sinatra中緩存響應的最佳方法是什麼?

我可以緩存大概5天左右的結果,根本沒有問題。我只是不是100%確定如何實現緩存。我如何去與Sinatra做這件事?

回答

11

就個人而言,我更喜歡使用redis來處理memcached上的這類事情。我有一個應用程序,我非常廣泛地使用redis,並以類似於您所描述的方式使用它。如果我撥打的電話沒有被緩存,頁面加載時間超過5秒,使用redis,加載時間下降到0.3秒左右。您也可以設置到期時間,可以很容易地更改。我會做這樣的事情來從緩存中檢索數據。

require 'redis' 
get '/my_data/:id' do 
    redis = Redis.new 
    if redis[params[:id]] 
    send_file redis[params[:id]], :type => 'application/json' 
    end 
end 

然後,當你想將數據保存到緩存中,或許是這樣的:

require 'redis' 
redis = Redis.new 
<make API calls here and build your JSON> 
redis[id] = json 
redis.expire(id, 3600*24*5) 
11
get '/my_data/:id' do 
    # security check for file-based caching 
    raise "invalid id" if params[:id] =~ /[^a-z0-9]/i 
    cache_file = File.join("cache",params[:id]) 
    if !File.exist?(cache_file) || (File.mtime(cache_file) < (Time.now - 3600*24*5)) 
    data = do_my_few_hundred_internal_requests(params[:id]) 
    File.open(cache_file,"w"){ |f| f << data } 
    end 
    send_file cache_file, :type => 'application/json' 
end 

別忘了mkdir cache

或者您可以使用memcache-client,但它會要求您在系統範圍內安裝memcached

+3

我喜歡這個解決辦法,因爲不依賴於分佈式緩存/ Redis的 –

相關問題