SpringCloud中Feign接口序列化配置为FastJson

先debug,看下

AbstractHttpMessageConverter

org.springframework.http.converter.AbstractHttpMessageConverter

SpringCloud中Feign接口序列化配置为FastJson_第1张图片

  • 注意到其默认实例是:

class org.springframework.http.converter.json.MappingJackson2HttpMessageConverter

  • Jackson相比FastJson,功能个可配置性相对较弱,想换成FastJson,如何处理?
@Configuration
public class ApplicationAutoConfiguration {

    /**
     * http、feign调用,序列化机制改为fastJson
     * @return
     */
    @Bean
    @Primary
    public HttpMessageConverters fastJsonHttpMessageConverters() {
        FastJsonHttpMessageConverter fastConverter = new FastJsonHttpMessageConverter();
        FastJsonConfig fastJsonConfig = new FastJsonConfig();
        fastJsonConfig.setSerializerFeatures(
                SerializerFeature.PrettyFormat,
                SerializerFeature.DisableCircularReferenceDetect,
                SerializerFeature.WriteBigDecimalAsPlain
        );
        fastConverter.setFastJsonConfig(fastJsonConfig);
        List supportedMediaTypes = new ArrayList<>();
        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
        fastConverter.setSupportedMediaTypes(supportedMediaTypes);
        HttpMessageConverter converter = fastConverter;
        return new HttpMessageConverters(converter);
    }
}
  • 咱在工程里定义一个配置类,配置一个HttpMessageConverters bean
  • 并将该bean标记为@Primary
  • 重启后再看看

SpringCloud中Feign接口序列化配置为FastJson_第2张图片

  • 此处需注意的是,不仅仅Feign接口调用改为了FastJson序列化,普通的RestController,也一样改为了FastJson

你可能感兴趣的:(#,知识总结,spring,json,ribbon,接口,ioc)