gpt4 book ai didi

ruby-on-rails - rails如何使用部分匹配删除缓存键

转载 作者:行者123 更新时间:2023-12-03 14:39:57 28 4
gpt4 key购买 nike

我正在使用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在键后使用通配符(*)进行部分匹配。

但我不知道生成的确切 key 是什么。现在我需要知道当我们使用数组作为键时它是如何产生键的。我的意思是如果我使用 [: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}*")

关于ruby-on-rails - rails如何使用部分匹配删除缓存键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19603598/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com