【问题标题】:rails how to delete cache key using partial matchrails如何使用部分匹配删除缓存键
【发布时间】:2013-11-05 09:12:38
【问题描述】:

我正在使用 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] 作为缓存键,缓存存储中的确切键是什么?

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    默认的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}*")
    

    【讨论】:

    • 这不适用于 memcache 作为数据存储。还有其他选择吗?
    • 小心在生产中使用delete_matchedPerformance note: this operation can be dangerous for large production databases, as it uses the Redis “KEYS” command, which is O(N) over the total number of keys in the database. Users of large Redis caches should avoid this method.rubydoc.info/gems/redis-activesupport/4.0.0/…
    猜你喜欢
    • 2014-10-07
    • 2019-03-08
    • 2021-05-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多