ruby-on-rails - 如何在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
解决方案
对于您的用例,使用哈希可能更好。您可以使用以下命令来实现:
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
推荐阅读
- ios - 在 Swift 中删除分组表中的行时崩溃
- java - REST 和数据库的对象命名约定
- javascript - 如果 divID 与数组中的字符串匹配,如何将多维数组中的数据用于 div 的样式?
- javascript - 部署问题(在 Heroku),承诺被拒绝,但代码在本地运行良好 -NodeJS/React
- python - 优化 Pandas df 以计算单词列表中的位置字符频率
- flutter - 如何将可滚动小部件转换为图像?
- python - 获取 pastebin 的单词并将它们转换为关键字列表
- c - CS50 PSET 5 Speller 无法正常工作(和 valgrind 问题)
- angular - 如何测试 Anguar 材质单选按钮?
- laravel - Laravel 更改项目名称问题