【问题标题】:How We can store and Retrieve Serializable Java Object as a value in Redis我们如何在 Redis 中将可序列化的 Java 对象作为值存储和检索
【发布时间】:2021-10-25 07:58:22
【问题描述】:

我们如何在 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;
    }

【问题讨论】:

标签: java serialization redis


【解决方案1】:

您可以使用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 参数将使您获得所需的确切类型。

【讨论】:

    猜你喜欢
    • 2015-07-01
    • 1970-01-01
    • 2021-06-03
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-10
    • 2014-10-15
    • 1970-01-01
    相关资源
    最近更新 更多