2013-07-27 2 views
1

Rails.cache.fetch을 간단하게하고 약 10 분 후에 만료 시키길 원합니다. 캐시는 외부 API에서 json 데이터로 채워집니다. 그러나 외부 API에 도달 할 수없는 경우가 있습니다. 따라서 캐시가 만료되고 새 json 데이터를 가져 오려고하면 캐시 내용이 유효하지 않게됩니다.새로운 값이 0이 아닌 경우 만 expires_in이있는 Rails.cache.fetch가 만료됩니다.

fetch_json이 유효한 데이터를 반환하면 Rails.cache.fetch를 캐시를 단지 어떻게 만듭니 까? 그러나 캐시는 새로운 유효한 데이터를 수신하면 10 분 후에 만료됩니다.

이것은 어떻게 했는가?하지만 작동하지 않습니다. 이 요지에서 더 나은 코드 강조 표시 : https://gist.github.com/i42n/6094528

나는 어떻게이 작업을 얻을 수 있습니까?

module ExternalApiHelper 

    require 'timeout' 
    require 'net/http' 

    def self.fetch_json(url) 
     begin 
      result = Timeout::timeout(2) do # 2 seconds 
       # operation that may cause a timeout 
       uri = URI.parse(url) 
       http = Net::HTTP.new(uri.host, uri.port) 
       request = Net::HTTP::Get.new(uri.request_uri) 
       response = http.request(request) 
       return JSON.parse(response.body) 
      end 
      return result 
     rescue 
      # if any error happens in the block above, return empty string 
      # this will result in fetch_json_with_cache using the last value in cache 
      # as long as no new data arrives 
      return "" 
     end 
    end 

    def self.fetch_json_with_cache(url, expire_time) 
     cache_backup = Rails.cache.read(url) 
     api_data = Rails.cache.fetch(url, :expires_in => expire_time) do 
      new_data = fetch_json(url) 
      if new_data.blank? 
       # if API fetch did not return valid data, return the old cache state 
       cache_backup 
      else 
       new_data 
      end 
     end 
     return api_data 
    end 

end 
+0

어떤 캐시 저장소를 사용하고 있습니까? –

+0

memcache => config.cache_store = : memory_store – funkenstrahlen

+0

아시겠지만 그 구성은 메모리 저장소를 사용하고 있다는 것을 의미합니다. memcache 저장소가 아닙니다. –

답변

관련 문제