【问题标题】:Rails.cache.fetch with expires_in only expire if new value is not nil带有 expires_in 的 Rails.cache.fetch 仅在新值不为 nil 时才过期
【发布时间】:2013-07-27 11:37:53
【问题描述】:

我想做一个简单的Rails.cache.fetch 并在大约 10 分钟后过期。缓存中填充了来自外部 API 的 json 数据。但是,有时无法访问外部 API。所以当缓存过期并尝试获取新的 json 数据时,缓存内容就会失效。

如果 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

【问题讨论】:

  • 你使用的是什么缓存存储?
  • memcache => config.cache_store = :memory_store
  • 您知道,该配置意味着您使用的是内存存储,而不是内存缓存存储

标签: ruby-on-rails caching fetch null


【解决方案1】:
猜你喜欢
  • 1970-01-01
  • 2019-09-29
  • 1970-01-01
  • 2016-03-12
  • 2013-03-09
  • 2013-10-07
  • 1970-01-01
  • 1970-01-01
  • 2021-01-21
相关资源
最近更新 更多