Nitesh Nandan
Nitesh Nandan

Reputation: 31

How We can store and Retrieve Serializable Java Object as a value in Redis

How We can store and Retrieve Serializable Java Object as a value in Redis.

I want to perform two operations in Redis

  1. storing the object
  2. 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;
    }

Upvotes: 3

Views: 1103

Answers (1)

Igor Flakiewicz
Igor Flakiewicz

Reputation: 793

You can convert your object to JSON and back using Jackson ObjectMapper. Then just store that json.

example:

private ObjectMapper mapper;

public boolean addToRedis(String key, Object obj) {
    try {
        redis.set(key, mapper.writeValueAsString(obj), Duration.ofSeconds(5000));
    } catch (Exception e) {
        e.printStackTrace();
        return false;
    }
    return true;
}

public <T> T getFromRedis(String key, Class<T> type) {
    try {
        return mapper.readValue(redis.get(key), type);
    } catch (Exception e) {
        e.printStackTrace();
    }
    return null;
}

In the getFromRedis method the use of generics and passing the type parameter will let you get the exact type you need.

Upvotes: 1

Related Questions