轨道如何使用部分匹配删除缓存键 [英] rails how to delete cache key using partial match

查看:72
本文介绍了轨道如何使用部分匹配删除缓存键的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am using redis-rails. For cache key I am using an array:

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 在部分匹配的键之后需要通配符(*)。

Now I need to remove all the cache with key matches with [self.class.name, :translated_attribute, id]. I know it has delete_matched that takes wildcard(*) after key for partial matching.

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

But I dont know what is the exact key generated. Now I need to know how it makes the key when we use array as key. I mean if I use [:foo, :bar, :dum] as cache key what will be the exact key in cache store?

推荐答案

默认的rails缓存密钥格式为:[class] / [id]-[timestamp]

The default rails cache key format is: [class]/[id]-[timestamp]

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

i usually dont use rails default cache key format, instead i create my own keys so it would be easier to manipulate in 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}*")

这篇关于轨道如何使用部分匹配删除缓存键的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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