Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Best way to store a list of java objects in Redis

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)

like image 933
user_ab Avatar asked Mar 09 '15 04:03

user_ab


People also ask

Can I store Java objects in Redis?

Yes! In my personal experience, we have chosen to serialize the Java objects as JSON and store that in Redis. And then, to read the value from Redis and deserialize a Java object from it.

Can Redis list 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.

How do I save a list in Redis?

You can't store like this in Redis. Instead you can use a reference of that list inside the value and make use of it. Here is an example: I have a hash contains NAME and urls. where urls is a list.

Can Redis store array?

We use various data structures (linked lists, arrays, hashes, etc) in our applications. They are usually implemented in memory but sometimes we need persistence AND speed. This is where in memory DB like Redis can be very useful.


1 Answers

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).

like image 133
zenbeni Avatar answered Sep 20 '22 13:09

zenbeni