How We can store and Retrieve Serializable Java Object as a value in Redis.
I want to perform two operations in Redis
- storing the object
- Retrieving it.
public boolean addToRedis(Object obj) {
try {
ByteArrayOutputStream out = new ByteArrayOutputStream();
ObjectOutputStream os = new ObjectOutputStream(out);
os.writeObject(obj);
redis.set("ObjetKey" , out.toByteArray(), Duration.ofSeconds(5000));
} catch (IOException e) {
e.printStackTrace();
}
return true;
}
public Object getObjectFromRedis() {
try {
// thows error, also tried with redis.get('ObjetKey').toString().getBytes() (corrupted byte exception)
ByteArrayInputStream in = new ByteArrayInputStream(redis.get('ObjetKey'));
ObjectInputStream is = new ObjectInputStream(in);
return (SomeObject) is.readObject();
} catch (Exception e) {
e.printStackTrace();
}
return null;
}