从Redis获取多个键值 [英] Getting multiple key values from Redis

查看:90
本文介绍了从Redis获取多个键值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用 Redis,我有几个问题.是否可以从键数组中获取值?

I'm currently playing around with Redis and i've got a few questions. Is it possible to get values from an array of keys?

示例:

users:1:name "daniel"
users:1:age  "24"

users:2:name "user2"
users:2:age  "24"

events:1:attendees "users:1", "users:2"

当我 redis.get events:1:attendees 返回 "users:1", "users:2".我可以遍历这个列表并获取用户:1,获取用户:2.但这感觉不对,有没有办法在1 get上获取所有与会者信息?!

When i redis.get events:1:attendees it returns "users:1", "users:2". I can loop through this list and get users:1, get users:2. But this feels wrong, is there a way to get all the attendees info on 1 get?!

在 Rails 中,我会做这样的事情:

In rails i would do something like this:

@event.attendees.each do |att|
  att.name
end

但在 redis 中我不能,因为它返回键而不是存储在该键上的实际对象.

But in redis i can't because it returns the keys and not the actual object stored at that key.

谢谢:)

推荐答案

对项目进行循环并同步访问每个元素的效率不是很高.使用 Redis 2.4,有多种方法可以做您想做的事:

Doing a loop on the items and synchronously accessing each element is not very efficient. With Redis 2.4, there are various ways to do what you want:

  • 使用排序命令
  • 使用流水线
  • 使用可变参数命令

在 Redis 2.6 中,您还可以使用 Lua 脚本,但这并不是真正必需的.

With Redis 2.6, you can also use Lua scripting, but this is not really required here.

顺便说一下,您描述的数据结构可以通过使用哈希来改进.您可以将用户数据分组到一个哈希对象中,而不是将它们存储在单独的键中.

By the way, the data structure you described could be improved by using hashes. Instead of storing user data in separate keys, you could group them in a hash object.

使用排序命令

您可以使用 Redis sort 命令在一次往返中检索数据.

You can use the Redis sort command to retrieve the data in one roundtrip.

redis> set users:1:name "daniel"
OK
redis> set users:1:age 24
OK
redis> set users:2:name "user2"
OK
redis> set users:2:age 24
OK
redis> sadd events:1:attendees users:1 users:2
(integer) 2
redis> sort events:1:attendees by nosort get *:name get *:age
1) "user2"
2) "24"
3) "daniel"
4) "24"

使用流水线

Ruby 客户端支持流水线(即能够向 Redis 发送多个查询并等待多个回复).

The Ruby client support pipelining (i.e. the capability to send several queries to Redis and wait for several replies).

keys = $redis.smembers("events:1:attendees")
res = $redis.pipelined do
   keys.each do |x|
      $redis.mget(x+":name",x+":age")
   end
end

上面的代码只会在两次往返中检索数据.

The above code will retrieve the data in two roundtrips only.

使用可变参数命令

MGET 命令可用于一次检索多个数据:

The MGET command can be used to retrieve several data in one shot:

redis> smembers events:1:attendees
1) "users:2"
2) "users:1"
redis> mget users:1:name users:1:age users:2:name users:2:age
1) "daniel"
2) "24"
3) "user2"
4) "24"

这里的费用也是两次往返.如果您可以保证要检索的密钥数量是有限的,则此方法有效.如果没有,流水线是一个更好的解决方案.

The cost here is also two roundtrips. This works if you can guarantee that the number of keys to retrieve is limited. If not, pipelining is a much better solution.

这篇关于从Redis获取多个键值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆