【问题标题】:How to set data in redis hash using ruby如何使用 ruby​​ 在 redis 哈希中设置数据
【发布时间】:2018-05-05 16:03:00
【问题描述】:

目前我正在通过执行以下操作将数据从活动记录缓存到 redis:

redis.rb

$redis = Redis::Namespace.new("bookstore", :redis => Redis.new)

authors_helper.rb

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

所以目前我正在使用基本的setget 来缓存并从redis 读取数据。

我想使用hmset 而不仅仅是set。 redis 完成这项工作的方式如下:

(只是一个例子)

HMSET user:1001 name "Mary Jones" password "hidden" email "mjones@example.com"

我的应用中的 authors 表包含以下字段:id,name,created_at,updated_at

使用hmset 的ruby 方法是什么,以便我可以在redis 哈希中缓存authors 数据?

【问题讨论】:

标签: ruby redis


【解决方案1】:

我认为您无法以这种方式保存所有作者。这是因为散列只能为每个键存储一个值。所以namecreated_at 不能是键,因为所有作者都需要为这些键存储自己的值,但每个键只能使用一次。

如果您使用 Ruby on Rails,则首选使用 Rails.cache - 这样您就不必担心 Rails 在 Redis 中存储对象的方式。

但是,如果您出于某种原因想使用hmset,我相信您能做的最好的事情是这样的:

authors = Author.all.flat_map { |author| [author.id.to_s, author.attributes.to_json] } $redis.hmset("authors", *authors_data)

第一行将返回如下内容:

['1', '{"name": "Mary Jones", "email": "m@example.com"}', '2', '{"name": "Another name", "email": "e@example.com"']

hmset 命令不接受数组,而是一个平面属性列表,这就是为什么在第二行中你需要将*authors_data 传递给函数。

然后,在内部它将如下所示:

{ '1' => '{"name": "Mary Jones", "email": "m@example.com"}', '2' => '{"name": "Another name", "email": "e@example.com"' }

稍后您可以执行$redis.hmget("authors", '1'),这将返回一个字符串'{"name": "Mary Jones", "email": "m@example.com"}'

【讨论】:

    猜你喜欢
    • 2021-02-05
    • 1970-01-01
    • 2016-10-04
    • 1970-01-01
    • 1970-01-01
    • 2014-10-11
    • 2012-07-15
    • 2020-03-24
    • 2019-04-30
    相关资源
    最近更新 更多