springboot2.x+Redis+Fastjson(坑已填),Redis使用Fastjson序列化

  • 去除springboot自带Jackson,必须去除,画重点,springboot2.x在引入了spring-boot-starter-data-redis的时候,如果不去除Jackson,即使配置了FastJsonHttpMessageConverter,依然不生效,所以必须去除,但是如果不引入spring-boot-starter-data-redis则不影响,目前不知道原因,就去除了吧
        
            org.springframework.boot
            spring-boot-starter-web
            
                
                    jackson-databind
                    com.fasterxml.jackson.core
                
            
        
        
            com.alibaba
            fastjson
            1.2.60
        
    
  • 配置GenericFastJson2JsonRedisSerializer
    package com.fengche.emsa.serializers;
    
    import com.alibaba.fastjson.JSON;
    import com.alibaba.fastjson.parser.ParserConfig;
    import com.alibaba.fastjson.serializer.SerializerFeature;
    import org.springframework.data.redis.serializer.RedisSerializer;
    import org.springframework.data.redis.serializer.SerializationException;
    import org.springframework.lang.Nullable;
    import org.springframework.stereotype.Component;
    
    @Component
    public class GenericFastJson2JsonRedisSerializer implements RedisSerializer {
    
        static final byte[] EMPTY_ARRAY = new byte[0];
    
        static {
            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
        }
    
        public byte[] serialize(@Nullable Object source) throws SerializationException {
            if (source == null) {
                return EMPTY_ARRAY;
            } else {
                try {
                    return JSON.toJSONBytes(source, SerializerFeature.WriteClassName);
                } catch (Exception var3) {
                    throw new SerializationException("Could not write JSON: " + var3.getMessage(), var3);
                }
            }
        }
    
        public Object deserialize(@Nullable byte[] source) throws SerializationException {
            if (isEmpty(source))
                return null;
            return JSON.parse(source);
        }
    
        static boolean isEmpty(@Nullable byte[] data) {
            return data == null || data.length == 0;
        }
    
    }
    
      
       
  • 配置RedisTemplate
        @Bean
        public RedisTemplate redisTemplate(LettuceConnectionFactory connectionFactory,StringRedisSerializer stringRedisSerializer,GenericFastJson2JsonRedisSerializer genericFastJson2JsonRedisSerializer){
            RedisTemplate redisTemplate = new RedisTemplate<>();
            redisTemplate.setKeySerializer(stringRedisSerializer);
            redisTemplate.setValueSerializer(genericFastJson2JsonRedisSerializer);
            redisTemplate.setConnectionFactory(connectionFactory);
            return redisTemplate;
        }
    
        @Bean
        public StringRedisSerializer stringRedisSerializer(){
            return new StringRedisSerializer();
        }
    
    
  • 配置FastJsonHttpMessageConverter
    /**
         * 添加fastjson为默认json解析
         *
         * @param converters
         */
        @Override
        public void configureMessageConverters(List> converters) {
            // 定义一个转换消息的对象
            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
            //fastConverter.getFastJsonConfig().getSerializeConfig().put(Json.class, com.fengche.education.config.SwaggerJsonSerializer.instance);
            // 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
            fastJsonConfig.setCharset(Charset.forName("UTF-8"));
            fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                    SerializerFeature.DisableCircularReferenceDetect);
            // 在转换器中添加配置信息
            fastConverter.setFastJsonConfig(fastJsonConfig);
            HttpMessageConverter converter = fastConverter;
            converters.add(converter);
        }
    
  • 如上就不会出错了,放心使用
  • 特别说明
    • 上述问题还有一种解决办法,代码如下:
        @Override
        public void configureMessageConverters(List> converters) {
            // 定义一个转换消息的对象
            
            /** 这段代码其实没有实际意义,但是加上它,fastjson就起作用,debug代码,其实没有移除任何的converter,但是加上就可以使fastjson生效,不加就不生效 */
            List> list = new ArrayList<>();
            for (HttpMessageConverter converter : converters) {
                if (converter.getClass().isAssignableFrom(MappingJackson2HttpMessageConverter.class)){
                    list.add(converter);
                }
            }
            converters.removeAll(list);
            /** ************************************************************************************************************************* */
            ParserConfig.getGlobalInstance().setAutoTypeSupport(true);
            FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
            // 添加fastjson的配置信息 比如 :是否要格式化返回的json数据
            FastJsonConfig fastJsonConfig = new FastJsonConfig();
            fastJsonConfig.setDateFormat("yyyy-MM-dd HH:mm:ss");
            fastJsonConfig.setCharset(Charset.forName("UTF-8"));
            fastJsonConfig.setSerializerFeatures(SerializerFeature.PrettyFormat,
                                                 SerializerFeature.DisableCircularReferenceDetect);
            // 在转换器中添加配置信息
            fastConverter.setFastJsonConfig(fastJsonConfig);
            HttpMessageConverter converter = fastConverter;
            converters.add(converter);
        }
    
    

    你可能感兴趣的:(springboot,redis,fastjson,springboot)