获取Rails缓存项的过期时间 [英] Get expiration time of Rails cached item

查看:65
本文介绍了获取Rails缓存项的过期时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在我的应用中使用的某个地方

Somewhere in my app I use

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

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

In another part of my app I want to figure out how much time it is left for that cache item.

我该怎么做?

推荐答案

这不是合法的方法,但是可以:

This is not a legal way, but it works:

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

read_entry 是受保护的方法,即由获取阅读和其他隐藏的方法,://://github.com/rails/rails/blob/master/activesupport/lib/active_support/cache.rb#L501 rel = nofollow noreferrer>存在?使用发送

read_entry is protected method that is used by fetch, read, exists? and other methods under the hood, that's why we use send.

如果存在则可能返回 nil 根本没有任何条目,因此将 try 与Rails一起使用,或将&。用于安全导航,或将 .tap {| e | e.expires_at除非e.nil? } 替换旧的红宝石。

It may return nil if there is no entry at all, so use try with Rails, or &. for safe navigation, or .tap{ |e| e.expires_at unless e.nil? } for old rubies.

因此,您会得到类似 1587122943.7092931 的内容。这就是为什么您需要 Time.now.to_f 的原因。使用Rails,您还可以使用 Time.current.to_f

As a result you will get something like 1587122943.7092931. That's why you need Time.now.to_f. With Rails you can use Time.current.to_f as well.

这篇关于获取Rails缓存项的过期时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆