首页 > 解决方案 > 我们如何在 Redis 中将可序列化的 Java 对象作为值存储和检索

问题描述

我们如何在 Redis 中将可序列化的 Java 对象作为值存储和检索。

我想在 Redis 中执行两个操作

  1. 存储对象
  2. 取回它。
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;
    }

标签: javaserializationredis

解决方案


您可以使用Jackson ObjectMapper 将对象转换为 JSON 并返回。然后只需存储该json。

例子:

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

getFromRedis方法中使用泛型并传递type参数将使您获得所需的确切类型。


推荐阅读