【发布时间】:2021-10-25 07:58:22
【问题描述】:
我们如何在 Redis 中将可序列化的 Java 对象作为值存储和检索。
我想在 Redis 中执行两个操作
- 存储对象
- 正在检索它。
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;
}
【问题讨论】:
-
只需将对象转换为 JSON 格式
标签: java serialization redis