Java object list is being deserialized and stored/retrieved in redis (not that troublesome)

        When I was working on a project today, there was a business scenario that required serializing a List<CardInfo> , storing it in redis, and extracting it and deserializing it into a List<CardInfo>

Serialize to 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);
    }
}

Be careful not to serialize the object into a normal String through toString(). This will make you cry during deserialization. It is very troublesome. Be good, listen to me, convert it to JSONString, and leave yourself a way out.


Deserialization

// 从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());

Guess you like

Origin blog.csdn.net/weixin_73077810/article/details/131955803