我正在尝试在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获取该作者?
获取作者的Helper方法
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发布于 2018-05-03 23:52:39
对于您的用例,使用散列可能更好。您可以使用以下命令来实现此目的:
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 datahttps://stackoverflow.com/questions/50153847
复制相似问题