Best way to save a list of Java objects in Redis

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

I am currently converting java objects to json strings and saving those strings in Redis, and I have a set in Redis to keep track of all this.

For instance: -

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

So, when I want to get the list of students, I first get the students set, and then iterate over it and get the json strings on these keys.

Just wondering if there is another better way to handle the storage script for a list of Java objects in Redis.

(I use redis as a cache)

+6
source share
3 answers

If you don't need to request java objects stored in redis (indexing, ratings ...), then you can just serialize them in bytearray using a library (e.g. Kryo) and save them in String in redis.Note that you you can serialize the whole set of Java objects in one redis line, just remember what class it is (collection type + object type), when you want to deserialize, you can, for example, define a smart key name for this purpose.

JSON will simply use more space and be more network intensive than other binary marshalling formats, if you do not need requests or data to be read by a person in redis, then it is normal (and more efficient) to store binary data in redis.

Note that if you use the jedis library (as you noted), you have Jedis methods that accept bytearrays as parameters instead of Java strings to send data as a C-String to Redis (without losing data in the process).

+6
source

Redis is more than a simple keystore. You can use hashes to store structured data in redis

HMSET student: 1 name "testOne" stream "computer science" http://redis.io/commands/hmset

to get the entire contents of the HGETALL student hash call: 1
you can also get uniform hash values ​​using hget
EXAMPLE HGET student: 1 name

+3
source

You can easily do this with Redisson . This is a Redis-based Java environment that supports many popular codecs (Jackson JSON, Avro, Smile, CBOR, MsgPack, Kryo, FST, LZ4, Snappy and JDK Serialization) and Redis such as Cluster, Sentinel, AWS Elasticache.

Here is an example of how to store a Java object for a list:

 RList<SomeObject> list = redisson.getList("anyList"); list.add(new SomeObject(1)); list.add(new SomeObject(2)); 
Interface

RList also implements the java.util.List interface. Pretty easy, right?

+1
source

Source: https://habr.com/ru/post/983526/


All Articles