Getting multiple key values from Redis

前端 未结 2 2021
遇见更好的自我
遇见更好的自我 2020-12-25 12:58

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?

Example:

users:1:name \"d         


        
相关标签:
2条回答
  • 2020-12-25 13:50

    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:

    • by using the sort command
    • by using pipelining
    • by using variadic parameter commands

    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.

    Using the sort command

    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"
    

    Using pipelining

    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.

    Using variadic parameter command

    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.

    0 讨论(0)
  • 2020-12-25 14:01

    You can use Redis' EVAL command to send it a Lua script that runs a loop "server side" and return the results in a block.

    0 讨论(0)
提交回复
热议问题