【问题标题】:Rails caching: replacement for expires_in on Rails.cache.fetchRails 缓存:替换 Rails.cache.fetch 上的 expires_in
【发布时间】:2011-09-24 04:31:00
【问题描述】:

在保持“获取或设置”缓存调用的简洁性的同时清除此警告的最佳方法是什么?我真的很喜欢不必执行 get,然后检查 nil,然后设置...

# DEPRECATION WARNING: Setting :expires_in on read has been deprecated in favor of setting it on write.

@foo = Rails.cache.fetch("some_key", :expires_in => 15.minutes) do
    some stuff
end

【问题讨论】:

  • 只想指出,在 Rails 4 中,俄罗斯娃娃缓存的趋势更加明显,无需过期时间。到期时间仍然可以更容易,但现在这有时是一种反模式。
  • Rails 4 不会对该语法给出弃用警告。

标签: ruby-on-rails


【解决方案1】:

我真的很喜欢不必执行 get,然后检查 nil,然后设置...

是的,您希望避免在每次通话时都这样做,但您仍然必须至少这样做一次。像这样简单的东西可能对你有用:

def smart_fetch(name, options, &blk)
  in_cache = Rails.cache.fetch(name)
  return in_cache if in_cache
  val = yield
  Rails.cache.write(name, val, options)
  return val
end

那么在你看来你可以这样做:

@foo = smart_fetch("some_key") do
  some stuff
end

请注意,Rails 缓存存储有一个默认到期时间,您可以在创建它时设置它,因此您可能不需要在每次调用时覆盖它,除非您需要不同的到期时间。

【讨论】:

    【解决方案2】:

    对@briandoll 提供的有用方法的小改动:

    def smart_fetch(name, options = {}, &blk)
      in_cache = Rails.cache.fetch(name)
      return in_cache if in_cache
      if block_given? 
        val = yield 
        Rails.cache.write(name, val, options) 
        return val 
      end 
    end
    

    【讨论】:

      【解决方案3】:

      【讨论】:

      • btw rails 3.1 通过将 rack::cache 添加到默认堆栈来稍微改变它:gist.github.com/958283
      • fresh_when 和 expires_when 是与 HTTP 响应相关的控制器方法;问题是关于通用数据缓存而不考虑 Web 服务。
      猜你喜欢
      • 2012-08-31
      • 1970-01-01
      • 2018-04-14
      • 1970-01-01
      • 1970-01-01
      • 2014-04-01
      • 2020-01-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多