Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using Redis to store array of hashes

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

like image 489
Richlewis Avatar asked May 31 '15 14:05

Richlewis


People also ask

Can Redis store arrays?

We use various data structures (linked lists, arrays, hashes, etc) in our applications.

Can Redis hash store a list?

Redis' data structures cannot be nested inside other data structures, so storing a List inside a Hash is not possible. Instead, use different keys for your servers' CPU values (e.g. server1:cpu ).

Does Redis support nested hash?

Redis doesn't support nested data structures, and specifically it doesn't support a Hash inside a Hash :) You basically have a choice between two options: either serialize the internal Hash and store it in a Hash field or use another Hash key and just keep a reference to it in a field of the outer Hash.

Can Redis store objects?

Object Storing Procedure. In the Redis, Everything can be stored as only key-value pair format. Key must be unique and storing an object in a string format is not a good practice anyway. Objects are usually stored in a binary array format in the databases.


1 Answers

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:

  • http://redis.io/commands/srandmember
  • http://redis.io/commands/sadd
  • http://redis.io/commands/spop
  • http://redis.io/commands/hget
  • http://redis.io/commands/hmset

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

like image 115
Mangat Rai Modi Avatar answered Sep 28 '22 05:09

Mangat Rai Modi