当前位置:网站首页>Redistemplate serialization

Redistemplate serialization

2022-06-22 14:42:00 wfsm

redisTemplate By default jdk Serialization scheme , When you save , There will be a bunch of prefixes ,
Write one yourself redisTemplate Change his serialization method

  • Use jackson
  @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
    
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);
        //  Set serializer  :  Use jackson serializers 
        Jackson2JsonRedisSerializer<Object> serializer = new Jackson2JsonRedisSerializer<>(Object.class);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);
        template.setHashValueSerializer(serializer);
        return template;
    }
  • Use fastjson
  @Bean
    public RedisTemplate<Object,Object> redisTemplate(RedisConnectionFactory redisConnectionFactory){
    
        RedisTemplate<Object, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        FastJsonRedisSerializer<Object> serializer = new FastJsonRedisSerializer<>(Object.class);

        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(serializer);

        template.setHashKeySerializer(new StringRedisSerializer());
        template.setHashValueSerializer(serializer);

        return template;
    }

Problems encountered :
redis Acquired jackson After serialization, there is a linkedHashmap ,, Need to put LinkedHashMap convert to Corresponding object ,, because springsecurity in User Realized UserDetails , Rewritten many get Method ,, image jackson This serialization tool relies on reflection to identify method properties ,get The method at the beginning is easy to mislead the serialization tool
jackson solve :

  1. Add annotations to the class @JsonIgnoreProperties(ignoreUnknown = true)
  2. Except for attribute getter Outside method , Do not use other methods get start
ObjectMapper objectMapper  = new ObjectMapper();
User user = objectMapper.readValue(objectMapper.writeValueAsString(obj), User.class);

quote :https://blog.csdn.net/woshisangsang/article/details/108420355
https://blog.csdn.net/huang812561/article/details/124706812

fastjson After serialization , yes JSONObject object , To the original object
fastjson solve

User user = JSON.parseObject(JSON.toJSONString(obj), User.class);

quote :https://blog.csdn.net/qq_34577234/article/details/125199552

原网站

版权声明
本文为[wfsm]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206221129567471.html