【问题标题】:Rails 4 skip cache in Rails.cache.fetchRails 4 在 Rails.cache.fetch 中跳过缓存
【发布时间】:2014-09-24 00:24:14
【问题描述】:

我的代码:

def my_method(path)
    Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
        # Calls Net::HTTP.get_response URI.parse path
        response = My::api.get path

        if response.status == 200
            JSON.parse response.body
        else
            nil # Here I need to prevent cache
        end
    end
end

返回nil 时我不会缓存,但它会.. 在这种情况下如何防止缓存?

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    一种不太优雅的方式是引发错误。

    def my_method(path)
      Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
        # Calls Net::HTTP.get_response URI.parse path
        response = My::api.get path
    
        raise MyCachePreventingError unless response.status == 200
    
        JSON.parse response.body
      end
    rescue MyCachePreventingError
      nil
    end
    

    如果有人有更好的方法我想知道

    【讨论】:

      【解决方案2】:

      另一种选择...

      def my_method(path)
          out = Rails.cache.fetch(path, expires_in: 10.minutes, race_condition_ttl: 10) do
              # Calls Net::HTTP.get_response URI.parse path
              response = My::api.get path
      
              if response.status == 200
                  JSON.parse response.body
              else
                  nil # Here I need to prevent cache
              end
          end
          Rails.cache.delete(path) if out.nil?
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2015-12-25
        • 1970-01-01
        • 2013-10-26
        • 2015-04-19
        • 2016-07-20
        相关资源
        最近更新 更多