【问题标题】:Get expiration time of Rails cached item获取 Rails 缓存项的过期时间
【发布时间】:2017-02-13 14:12:40
【问题描述】:

我在应用中使用的某处

Rails.cache.write 'some_key', 'some_value', expires_in: 1.week

在我的应用程序的另一部分,我想弄清楚该缓存项还剩下多少时间。

我该怎么做?

【问题讨论】:

  • 缓存存储是内部的,所以你不能。但是您可以为某些缓存存储更新 ttl(例如 touch 用于 memcached)
  • 我使用 Redis。有没有办法touch在那里缓存项目?
  • 在redis中它被称为expire(这里是例子如果你使用redis-rb适配器github.com/redis/redis-rb/wiki/Redis-rb-Overview

标签: ruby-on-rails caching


【解决方案1】:

这不是一种合法的方式,但它有效:

expires_at = Rails.cache.send(:read_entry, 'my_key', {})&.expires_at
expires_at - Time.now.to_f if expires_at

read_entryfetchreadexists? 和其他底层方法使用的受保护方法,这就是我们使用 send 的原因。

如果根本没有条目,它可能会返回 nil,所以在 Rails 中使用 try,或 &. 用于安全导航,或 .tap{ |e| e.expires_at unless e.nil? } 用于旧红宝石。

因此,您将获得类似1587122943.7092931 的信息。这就是您需要Time.now.to_f 的原因。在 Rails 中,您也可以使用 Time.current.to_f

【讨论】:

  • Rails.cache.send(:read_entry, key).instance_variable_get(:@expires_in) 也可以工作,@expires_in 保存过期值,因此无需进一步操作即可对其进行比较。
  • @SebastianPalma 但这不会告诉你原来的问题是how much time it is left
  • 作为@NickRoz 的后续行动,expires_at 的外观如下:@expires_in ? @created_at + @expires_in : nil。因此它将created_atexpires_in 值都存储在缓存中,用于确定缓存条目是否过期。整洁!
【解决方案2】:

哇。我就是来找这个的。答案是否定的,真可惜。

那么,我不喜欢的解决方案是缓存过期时间。

Rails.cache.write 'some_key', ['some_value', 1.week.from_now], expires_in: 1.week

我想这不是世界末日,只是你必须记住它是作为数组存储的。

或者,您可以使用可缓存模块稍微抽象一下功能。那么你就不必“记住”任何东西了。

【讨论】:

    【解决方案3】:

    这有助于我获取特定缓存键的剩余 TTL(在 Redis 缓存存储中):

    Rails.cache.redis.ttl("#{Rails.cache.options[:namespace]}:#{my_key}")
    

    【讨论】:

      【解决方案4】:

      更新,您可能需要先规范化密钥

      normalized_key = Rails.cache.send(:normalize_key, key, {})
      expires_at = Rails.cache.send(:read_entry, normalized_key, {}).expires_at
      expires_at - Time.now.to_f if expires_at
      

      【讨论】:

        猜你喜欢
        • 2012-04-23
        • 1970-01-01
        • 2011-11-10
        • 1970-01-01
        • 2013-01-02
        • 2012-02-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多