Rails如何使用部分匹配删除缓存键

2024-03-22

我正在使用 redis-rails。对于缓存键,我使用一个数组:

Rails.cache.fetch([self.class.name, :translated_attribute, id, field, I18n.locale]) do
  self.read_attribute field, locale: I18n.locale
end

现在我需要删除所有键与 [self.class.name, :translated_attribute, id] 匹配的缓存。我知道它有delete_matched在键后使用通配符(*)进行部分匹配。

但我不知道生成的确切密钥是什么。现在我需要知道当我们使用数组作为键时它是如何生成键的。我的意思是,如果我使用 [:foo, :bar, :dum] 作为缓存键,缓存存储中的确切键是什么?


默认的 Rails 缓存键格式为:[class]/[id]-[timestamp]

我通常不使用 Rails 默认缓存密钥格式,而是创建自己的密钥,这样在 Redis 中操作会更容易。

cache_key = "#{self.class.name}/#{translated_attribute}/#{id}/#{field}/#{I18n.locale}"

Rails.cache.fetch(cache_key) do
  self.read_attribute field, locale: I18n.locale
end

Rails.cache.delete(cache_key)
Rails.cache.delete_matched("#{self.class.name}*#{id}*")
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

Rails如何使用部分匹配删除缓存键 的相关文章

随机推荐