简体   繁体   English

如何在 Ruby on Rails 上列出内存缓存存储中的键?

[英]How can I list the keys in the in-memory cache store on Ruby on Rails?

I am using Rails 3.我正在使用 Rails 3。

How can I list the keys in the in-memory cache store on Ruby on Rails?如何在 Ruby on Rails 上列出内存缓存存储中的键?

Rails.cache.instance_variable_get(:@data).keys

ActiveSupport::Cache::MemoryStore doesn't provide a way to access the store's keys directly (and neither does its parent class ActiveSupport::Cache::Store ). ActiveSupport::Cache::MemoryStore不提供直接访问存储键的方法(其父类ActiveSupport::Cache::Store也不提供)。

Internally MemoryStore keeps everything in a Hash called @data , however, so you could monkey-patch or subclass it to get the keys, eg:但是,在内部 MemoryStore 将所有内容保存在名为@data的哈希中,因此您可以对它进行猴子补丁或子类化以获取密钥,例如:

class InspectableMemoryStore < ActiveSupport::Cache::MemoryStore
  def keys
    @data.keys
  end
end

ActionController::Base.cache_store = InspectableMemoryStore.new

Rails.cache.keys # => [ "foo", ... ]

This comes with the usual caveat, however: MemoryStore's internal implementation may change at any time and @data may disappear or be changed to something that doesn't respond_to? :keys然而,这带有通常的警告:MemoryStore 的内部实现可能随时更改,@ @data可能会消失或更改为不respond_to? :keys respond_to? :keys . respond_to? :keys A smarter implementation might be to override the write and delete methods (since, as part of the public API, they're unlikely to change unexpectedly) to keep your own list of keys, eg:更聪明的实现可能是覆盖writedelete方法(因为作为公共 API 的一部分,它们不太可能意外更改)以保留您自己的密钥列表,例如:

class InspectableMemoryStore < ActiveSupport::Cache::MemoryStore
  def write *args
    super

    @inspectable_keys[ args[0] ] = true
  end

  def delete *args
    super

    @inspectable_keys.delete args[0]
  end

  def keys
    @inspectable_keys.keys
  end
end

This is a very naive implementation, and of course keeping the keys in an additional structure takes up some memory, but you get the gist.这是一个非常幼稚的实现,当然,将键保存在一个额外的结构中会占用一些内存,但你明白了要点。

在 Rails 6 中,Redis 用作缓存存储

Rails.cache.redis.keys

If you don't need to access the keys dynamically, an easier approach is locating the directory where the cache is stored.如果您不需要动态访问密钥,更简单的方法是定位存储缓存的目录。 A file is created for each entry.为每个条目创建一个文件。

In my case this was at "APP_ROOT/tmp/cache", but you can easily locate it by going to rails console and typing在我的情况下,这是在“APP_ROOT/tmp/cache”,但您可以通过转到 rails 控制台并键入轻松找到它

1.8.7 :030 >   Rails.cache.clear
 => ["path_to_rails_app/tmp/cache/6D5"]

Fetch all keys:获取所有密钥:

Rails.cache.data.keys

Read the specific key读取特定键

Rails.cache.read("cache_key")

Delete one key from keys:从键中删除一个键:

Rails.cache.delete("cache_key")

Flush out the keys冲出钥匙

Rails.cache.clear

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM