首页 > 解决方案 > 如何在rails应用程序中使用id获取redis数据

问题描述

我正在尝试在 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-railsredis

解决方案


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

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

推荐阅读