Java对象列表正反序列化在redis中存储 / 获取(没有那么麻烦)

        今天在赶项目的时候,有一个业务场景,一个要求将一个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());

猜你喜欢

转载自blog.csdn.net/weixin_73077810/article/details/131955803
今日推荐