java - 我们如何在 Redis 中将可序列化的 Java 对象作为值存储和检索
问题描述
我们如何在 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;
}
解决方案
您可以使用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
参数将使您获得所需的确切类型。
推荐阅读
- c++ - 了解以硬编码值作为参数的 NiFpga_MergeStatus() 函数
- twig - Twig For Loop 无法迭代嵌套模式属性
- javascript - chrome.notifications.onClosed 在 google chrome 扩展的 background.js 中不起作用
- firebase - 如何重新生成 Firebase 远程配置 API 密钥?
- ruby - 在 Travis CI 的矩阵中使用带有 Ruby 和 Shell 的多个操作系统
- python - xlwings:如何检测是否从 VBA 模块调用了 python 函数?
- woocommerce - 我如何知道每种产品的库存历史记录?
- kotlin - 如何使用 Graphql-kotlin 查询同时返回数据字段和错误字段
- tensorflow - 如何将 CNN 模型输入张量从形状 (? , 128, 128, 3 ) 转换为 (? , ? , ? , 3)?
- python - 如何从另一个文件(original.csv)向我的文件(modifiedFlights.csv)添加一列