Using Redis Java client Jedis
How can I cache Java Object?
-
Serialize it using your favorite marshaller, kryo or json for instance.zenbeni– zenbeni2015-05-15 08:51:33 +00:00Commented May 15, 2015 at 8:51
-
stackoverflow.com/questions/12279117/… I think my question has answered at this thread.DP Dev– DP Dev2015-05-15 13:56:54 +00:00Commented May 15, 2015 at 13:56
3 Answers
you should convert your object as a json string to store it, then read the json and transform it back to your object.
you can use Gson in order to do so.
//store
Gson gson = new Gson();
String json = gson.toJson(myObject);
jedis.set(key,json);
//restore
String json = jedis.get(key);
MyObject object=gson.fromJson(json, MyObject.class);
1 Comment
You can't store objects directly into redis. So convert the object into String and then put it in Redis. In order to do that your object must be serialized. Convert the object to ByteArray and use some encoding algorithm (ex base64encoding) and convert it as String then store in Redis. While retrieving reverse the process, convert the String to byte array using decoding algorithm (ex: base64decoding) and the convert it to object.
3 Comments
I would recommend to use more convenient lib to do it: Redisson - it's a Redis based framework for Java. It has some advantages over Jedis
- You don't need to serialize/deserialize object by yourself each time
- You don't need to manage connection by yourself
- You can work with Redis asynchronously
Redisson does it for you and even more. It supports many popular codecs like Jackson JSON, Avro, Smile, CBOR, MsgPack, Kryo, FST, LZ4, Snappy and JDK Serialization.
RBucket<AnyObject> bucket = redisson.getBucket("anyObject");
// set an object
bucket.set(new AnyObject());
// get an object
AnyObject myObject = bucket.get();