Java Redis Hash 获取 Pod 对象报错解决方法
Java Redis Hash 获取 Pod 对象报错解决方法
在使用 Java Redis Template 获取 Hash 中存储的 Pod 对象时,可能会遇到以下报错:
public Map<String, pod> getPods(String key){
Map<Object, Object> entries = redisTemplate.opsForHash().entries(nxConfig.getKeyPrefix() + key);
return entries.entrySet().stream().collect(Collectors.toMap(entry -> entry.getKey().toString(), Map.Entry::getValue));
}
该报错通常是因为 Redis 中存储的 Hash 数据类型不匹配导致的。解决方法是将 Map<Object, Object> 改为 Map<String, pod>,并在 stream 中使用 entry.getKey().toString(),如下所示:
public Map<String, pod> getPods(String key){
Map<String, pod> entries = new HashMap<>();
Map<Object, Object> map = redisTemplate.opsForHash().entries(nxConfig.getKeyPrefix() + key);
for (Map.Entry<Object, Object> entry : map.entrySet()) {
String hashKey = entry.getKey().toString();
pod value = (pod) entry.getValue();
entries.put(hashKey, value);
}
return entries;
}
解释:
Map<Object, Object>无法直接转换为Map<String, pod>,因此需要手动遍历Map<Object, Object>,将key转为String类型,value转为pod类型,并放入新的Map<String, pod>中。entry.getKey().toString()用于将Object类型的 key 转为String类型。pod value = (pod) entry.getValue();用于将Object类型的 value 转为pod类型。
通过以上修改,即可成功获取 Redis Hash 中存储的 Pod 对象。
原文地址: https://www.cveoy.top/t/topic/oBKi 著作权归作者所有。请勿转载和采集!