簡體   English   中英

rails:如何從 Rails.cache 中獲取所有鍵值

[英]rails: how to get all key-values from Rails.cache

我想用 Rails.cache(memory_store) 維護一個用戶在線/離線列表。

基本上,如果一個請求/user/heartbeat?name=John到達 Rails 服務器,它將簡單地:

def update_status
  name = params.require(:name)
  Rails.cache.write(name, Time.now.utc.iso8601, expires_in: 6.seconds)
end

但是我怎樣才能獲得存儲在 Rails.cache 中的所有數據,如下所示?

def get_status
  # wrong codes, as Rails.cache.read doesn't have :all option.
  ary = Rails.cache.read(:all)
  # deal with array ...
end

google了一下,好像Rails.cache沒有提供直接獲取所有數據的方法。 還是有更好的方法來存儲數據?

我正在使用Rails 5.0.2

謝謝你的時間!

您可以使用代碼獲取所有密鑰:

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

如果你有 redis,你可以使用諸如Rails.cache.redis.keys

此外,您可以迭代鍵以獲取它們的值並將它們全部顯示出來

keys = Rails.cache.instance_variable_get(:@data).keys
keys.each{|key| puts "key: #{key}, value: #{Rails.cache.fetch(key)}"}

或直接將它們全部映射為:

key_values = Rails.cache.instance_variable_get(:@data).keys.map{|key| {key: key, value: Rails.cache.fetch(key)}}

此外,我會事先檢查鍵的數量,以確保我不會想出一個巨大的對象(如果是這樣,將生成的 key_value 數組限制為例如前 1000 個項目)。 你可以使用:

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

或者看看 stats 命令的最后一行:

Rails.cache.stats

如果您使用的是 Redis,所有答案似乎都不起作用。 相反,您將不得不使用 redis-rb:

redis = Redis.new(url: ENV["REDIS_URL"])
redis.keys("*")

以上答案對我有幫助。 通過循環可以看到現有的緩存值

 Rails.cache.redis.keys.each{ |k| puts k if Rails.cache.exist?(k)}

如果您有連接池,請嘗試:

Rails.cache.redis.with do |conn|
  conn.keys
end

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM