我目前使用 Rails.cache.fetch,cache_store 使用 redis-store gem(修改为使用 YAML 而不是正常编码)。现在,我有以下代码:
Rails.cache.fetch("foobar", expires_in: 1.week) do
User.all.to_a.each do |user|
user.email = "foobar"
end
end
这将把用户的 ruby 数组的 YAML 版本存储到单个键值中。我想有效地将此列表分解为多个键,以便以后能够检索所有值而不是访问数据库。
我应该怎么做?我正在考虑一个哈希列表,但它似乎效率不高,因为我仍然需要在列表中查找特定的哈希以仅更新一个用户。
最佳答案
据我从您的评论中了解到:
I need to be able to look up any user by an attribute, and fetch the rest of their data through Redis.
您希望通过某些属性在商店中查找用户,我们假设它将是电子邮件。 所以你可以使用 redis hash data结构来完成你的任务。
有两个简单的命令可以处理结构:
HGET
在O(1)
中工作
HSET
以O(1)
运行
所以你可以看到性能很好。
通过 redis-cli 的示例:
hmset user:1000 username antirez birthyear 1977 verified 1 => OK
hget user:1000 username => antirez
Redis gem(我已经检查过 3.2.1 版本)具有使用此结构的接口(interface)。
A hash with a few fields (where few means up to one hundred or so) is stored in a way that takes very little space, so you can store millions of objects in a small Redis instance.
While Hashes are used mainly to represent objects, they are capable of storing many elements, so you can use Hashes for many other tasks as well. Every hash can store up to 232 - 1 field-value pairs (more than 4 billion).
关于ruby-on-rails - 将所有用户存储到 Redis 而不是编码数组的有效方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38179659/