Best way to store a list of java objects in Redis

user_ab picture user_ab · Mar 9, 2015 · Viewed 30.6k times · Source

It would be great if someone could suggest me on what would be the best way to store a list of java objects in Redis.

Currently, I'm converting the java objects into json strings and storing those strings in Redis and I have a set in Redis to keep track of all these.

For eg :-

SET student:1 '{"name":"testOne","stream":computer science}'
SET student:2 '{"name":"testTwo","stream":electronics}'
SADD students 1
SADD students 2

So when ever I want to fetch the list of students, I first get the set students and then iterate over it and get the json strings at those keys.

Just wondering if there is any other better way to handle the scenario of storing a list of java objects to Redis.

(I'm using redis as a cache)

Answer

zenbeni picture zenbeni · Mar 10, 2015

If you don't need querying your java objects stored in redis (indexation, scores...), then you can just serialize them to a bytearray with a library (Kryo for instance) and store them in a String in redis. Note that you can serialize a whole collection of java objects in one redis string, just remember which class it is (collection type + type of object) when you want to deserialize, you can define a clever key name for this purpose for instance.

JSON will just use more space and will be more network intensive than other binary marshalling formats, if you don't need queries or human readable data in redis, then it is fine (and more performant) to store binary data in redis.

Note that if you are using jedis library (as you tagged it) you have methods on Jedis that take bytearrays as parameters instead of Java strings in order to send data as C-String to Redis (no data loss in the process).