6

I have just started to look at Redis and would like to be able to store an Array of hashes, where I can pop a random key/value out and then put it back in when I need to.

So in Ruby I would have something like this

users = [{ username: "user1", password: "password"}, { username: "user2", password: 'password'}]

So if I wanted to get a random key/value object from the Array I would do something like this

@user = users.shuffle!.pop

And then to put it back into the array

users.push(@user)

The idea for using Redis is that I have two processes (Ruby based app) that need to share a pool of users at the same time. Once a process has finished with a user I want it to put it back into the pool.

Could anyone point me in the right direction please

Thanks

ROOT
  • 11,363
  • 5
  • 30
  • 45
Richlewis
  • 15,070
  • 37
  • 122
  • 283
  • If I understand correctly, You need to pull a Key/Value pair from Redis at random, and block it, i.e. no other process could use it until the process 1 is finished? – Mangat Rai Modi May 31 '15 at 15:26

1 Answers1

13

You could Redis Hash to store a user info and Redis Set to store all these hashes together.

Steps:

  1. Make a redis Hash with HSET command:HMSET userId_653 username "Tom" password "gd36e3hd38d3jdj3yd3hd38"
  2. Add this hash in the set called users: SADD users userId_653. This set contains all the users.
  3. Get a random user key from the set: SRANDMEMBER users. It will return userId_653
  4. Get the corresponding values from hash using HGET userId_653 username
  5. If you need to pop the key simply do SPOP users after step 3. and SADD again after processing in step 4.

A similar question for better understanding: Redis how to store associative array

References:

PS: I have no experience in Ruby. Look for suitable Redis Ruby API which would support all these operations!

Thomas Gratier
  • 2,311
  • 1
  • 14
  • 15
Mangat Rai Modi
  • 5,397
  • 8
  • 45
  • 75
  • 1
    thanks for your answer, after i have finished with the random user i can just SET the hash again and add it back to users? The idea being the set just gets repopulated once a user has been finished with.. Think i get it all though, those references will help – Richlewis May 31 '15 at 16:00
  • No need to set the hash again. If you are not editing user Info. As all your processes will access users from set, simply popping and adding in the set will suffice :) – Mangat Rai Modi May 31 '15 at 16:05