Using jedis How to cache Java object

23,584

Solution 1

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

Solution 2

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.

Solution 3

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

  1. You don't need to serialize/deserialize object by yourself each time
  2. You don't need to manage connection by yourself
  3. 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();
Share:
23,584
DP Dev
Author by

DP Dev

Updated on October 25, 2021

Comments

  • DP Dev
    DP Dev over 2 years

    Using Redis Java client Jedis
    How can I cache Java Object?

  • DP Dev
    DP Dev about 9 years
    But is this recommended practices to do so with Redis ?
  • Karthikeyan Gopall
    Karthikeyan Gopall about 9 years
    If you really want to store the object in Redis this is the only way. It's upto you to store the object directly or splitting up and storing individual values in objects as a hash or something.
  • Madhav
    Madhav almost 8 years
    This is a good answer. But you don't necessarily need to convert into String. You can store byte[] in Redis which will save you from converting to/from String. Good post on deserializing object to byte[] stackoverflow.com/questions/2836646/…
  • Srini
    Srini almost 6 years
    This is the easiest way to store Java objects in Redis.. You are awesome!!!
  • JorgeGarza
    JorgeGarza about 5 years
    Beware this ads up a layer of complexity for your application since after a change on the signature of your clases Redisson won't be able to retrieve the serialized object "as is"
  • Nikita Koksharov
    Nikita Koksharov about 5 years
    @JorgeGarza I'm afraid you're mistaken. Redisson supports about 10 codecs. If you use JDK Serialization codec, for example, it won't be a problem. You can even write your own codec. Which codec do you use?