今天在赶项目的时候,有一个业务场景,一个要求将一个List<CardInfo>序列化后存储到redis中以及将其提取出来反序列化为List<CardInfo>
序列化为JSONString:
@Component
public class RedisUtil {
@Resource
StringRedisTemplate stringRedisTemplate;
public List<String> getListFromRedis(String key) {
return stringRedisTemplate.opsForList().range(key, 0, -1);
}
/**
* 序列化java对象为json字符串,而不是一个String(这样子反序列化才能实现)
*/
public void saveJsonStringToRedis(String key, List<?> dataList, Integer validTime) {
List<String> stringDataList = dataList.stream()
.parallel()
.filter(Objects::nonNull)
.map(data -> {
try {
return new ObjectMapper().writeValueAsString(data);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList());
stringRedisTemplate.opsForList().rightPushAll(key, stringDataList);
stringRedisTemplate.expire(key, validTime, TimeUnit.MINUTES);
}
}
注意这里不要将该对象通过toString()序列化为一个普通String,这样子在反序列化的时候有的你哭,很麻烦的,乖,听我的,转JSONString,给自己留条后路
反序列化
// 从redis中找到他刚才选择的数据
List<String> cardInfoListString = redisUtil.getListFromRedis(userId + Constants.SPECIAL_PAY_SUFFIX);
if (cardInfoListString == null || cardInfoListString.size() == 0) {
return false;
}
ObjectMapper mapper = new ObjectMapper();
List<CardInfo> cardInfoList = cardInfoListString.stream()
.parallel()
.map(cardInfo -> {
try {
return mapper.readValue(cardInfo, CardInfo.class);
} catch (JsonProcessingException e) {
throw new RuntimeException(e);
}
})
.collect(Collectors.toList());