获取 Rails 缓存项的过期时间

bla*_*0ne 9 caching ruby-on-rails

在我的应用程序的某个地方我使用

Rails.cache.write 'some_key', 'some_value', expires_in: 1.week
Run Code Online (Sandbox Code Playgroud)

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

我怎么做?

Nic*_*Roz 8

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

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

read_entry是受保护的所使用的方法获取阅读存在?以及引擎盖下的其他方法,这就是我们使用send.

nil如果根本没有条目,它可能会返回,因此请try与 Rails 一起使用,或&.用于安全导航,或.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` 保存过期值,因此可以进行比较而无需进一步操作。 (2认同)
  • @SebastianPalma 但这不会告诉你最初的问题是什么,即“还剩多少时间”。 (2认同)

Ton*_*ony 5

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

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

Rails.cache.write 'some_key', ['some_value', 1.week.from_now], expires_in: 1.week
Run Code Online (Sandbox Code Playgroud)

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

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


小智 5

这对我来说可以获取特定缓存键的剩余 TTL(在 Redis 缓存存储中):

Rails.cache.redis.ttl("#{Rails.cache.options[:namespace]}:#{my_key}")
Run Code Online (Sandbox Code Playgroud)