【问题标题】:How to fetch redis data using id in rails app如何在rails应用程序中使用id获取redis数据
【发布时间】:2018-05-03 11:22:15
【问题描述】:

我正在尝试在 rails 应用程序上实现 redis 缓存。到目前为止,我可以使用 redis 缓存来缓存活动记录数据。我可以使用get 方法一次获取所有记录。但是我很难弄清楚如何使用 id 获取单个记录,因为 redis 生成的数据是字符串数据类型。

以下是redis缓存的数据:

"set" "bookstore:authors" "[{\"id\":1,\"name\":\"Stephenie Meyer\",\"created_at\":\"2018-05-03T10:58:20.326Z\",\"updated_at\":\"2018-05-03T10:58:20.326Z\"},{\"id\":2,\"name\":\"V.C. Andrews\",\"created_at\":\"2018-05-03T10:58:20.569Z\",\"updated_at\":\"2018-05-03T10:58:20.569Z\"}]

现在我正在打电话

authors = $redis.get('authors')

显示所有作者。

如何使用他的 id 获取单个作者?

获取作者的辅助方法

def fetch_authors
    authors = $redis.get('authors')

    if authors.nil?
      authors = Author.all.to_json
      $redis.set("authors", authors).to_json
      $redis.expire("authors", 5.hour.to_i)
    end
    JSON.load authors
end

【问题讨论】:

    标签: ruby-on-rails redis


    【解决方案1】:

    对于您的用例,使用哈希可能更好。您可以使用以下命令来实现:

    HSET bookstore:authors 1 "<author json>"
    HGET bookstore:authors 1 // Returns that author's json data
    

    或者您可以单独存储每个作者:

    SET bookstore:authors:1 <author_json>
    GET bookstore:authors:1 // Returns that author's json data
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-15
      • 2010-11-07
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-25
      • 1970-01-01
      相关资源
      最近更新 更多