【问题标题】:rails: how to get all key-values from Rails.cacherails:如何从 Rails.cache 中获取所有键值
【发布时间】:2017-10-02 20:51:46
【问题描述】:

我想用 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

感谢您的宝贵时间!

【问题讨论】:

    标签: ruby-on-rails caching


    【解决方案1】:

    您可以通过代码获取所有密钥:

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

    【讨论】:

    • >> >> keys = Rails.cache.instance_variable_get(:@data).keys keys = Rails.cache.instance_variable_get(:@data).keys NoMethodError(未定义的方法'keys'为nil:无类)
    • 我用 rails 5.2.1 测试导致同样的错误。你可以试试Rails.cache.redis.keys
    • /!\ 请注意,它不适用于所有缓存后端:例如,它适用于 :memory_store,但不适用于 Redis (:redis_cache_store)。
    【解决方案2】:

    如果你有redis,你可以使用Rails.cache.redis.keys之类的东西

    【讨论】:

      【解决方案3】:

      此外,您可以对键进行迭代以获取它们的值并全部显示

      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
      

      【讨论】:

      • /!\ 请注意,它不适用于所有缓存后端:例如,它适用于 :memory_store,但不适用于 Redis (:redis_cache_store)。
      【解决方案4】:

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

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

      【讨论】:

        猜你喜欢
        • 2013-01-16
        • 1970-01-01
        • 2019-11-01
        • 1970-01-01
        • 1970-01-01
        • 2018-01-04
        • 2016-06-02
        • 1970-01-01
        • 2018-04-14
        相关资源
        最近更新 更多