Spring Cloud Feign 配置 FastJson

Updated on in 编程技术 with 0 views and 0 comments

项目集成 FastJson 解析框架,一般都会添加一个配置文件,如下:

 1@Configuration
 2public class CustomFastJsonConfig {
 3
 4    @Bean
 5    FastJsonHttpMessageConverter fastJsonHttpMessageConverter(){
 6        //1.需要定义一个convert转换消息的对象
 7        FastJsonHttpMessageConverter converter = new FastJsonHttpMessageConverter();
 8        //2:添加fastJson的配置信息
 9        FastJsonConfig fastJsonConfig = new FastJsonConfig();
10        fastJsonConfig.setSerializerFeatures(
11                // 是否输出值为null的字段,默认为false
12                SerializerFeature.WriteMapNullValue,
13                // 将Collection类型字段的字段空值输出为[]
14                SerializerFeature.WriteNullListAsEmpty,
15                // 将字符串类型字段的空值输出为空字符串
16                SerializerFeature.WriteNullStringAsEmpty,
17                // 将数值类型字段的空值输出为0
18                SerializerFeature.WriteNullNumberAsZero,
19                //Boolean字段如果为null,输出为false,而非null
20                SerializerFeature.WriteNullBooleanAsFalse,
21                //SerializerFeature.WriteDateUseDateFormat,
22                //枚举字段输出为枚举值
23                SerializerFeature.WriteEnumUsingToString,
24                // 禁用循环引用
25                SerializerFeature.DisableCircularReferenceDetect);
26        //这个日期格式是全局格式:yyyy-MM-dd HH🇲🇲ss
27        fastJsonConfig.setDateFormat("yyyy-MM-dd HH🇲🇲ss");
28        fastJsonConfig.setCharset(StandardCharsets.UTF_8);
29
30        //3处理中文乱码问题
31        List<MediaType> fastMediaTypes = new ArrayList<>();
32        fastMediaTypes.add(MediaType.APPLICATION_JSON);
33
34        //4.在convert中添加配置信息.
35        converter.setSupportedMediaTypes(fastMediaTypes);
36        converter.setFastJsonConfig(fastJsonConfig);
37        return converter;
38    }
39}

但是,当 Spring Cloud 微服务项目使用 Feign 的时候,有一个比较坑的地方,就是,Feign 并不共用 Spring MVC 的消息转换器链,而且它默认使用的是 Jackson JSON 解析库,而项目使用的又是 FastJson,这会导致混乱,甚至出现序列化/反序列化错误。

就比如上边这个配置,A 应用通过 Feign 调用 B 应用的搜索接口,接口参数是一个实体对象,其中实体对象有一个 Date 类型的时间属性参数 downDate,那么,由于上边配置的日期格式是:yyyy-MM-dd HH🇲🇲ss,在通过 Feign 调用的时候,就会产生一个异常:

 1{"timestamp":"2020-03-29T03:54:55.014+0000","status":400,"error":"Bad Request","message":"JSON parse error: 
 2Cannot deserialize value of type `java.util.Date` from String \"2020-03-03 00:00:00\": 
 3not a valid representation (error: Failed to parse Date value '2020-03-03 00:00:00': 
 4Cannot parse date \"2020-03-03 00:00:00\": 
 5while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)); 
 6nested exception is com.fasterxml.jackson.databind.exc.InvalidFormatException: 
 7Cannot deserialize value of type `java.util.Date` from String \"2020-03-03 00:00:00\": 
 8not a valid representation (error: Failed to parse Date value '2020-03-03 00:00:00': 
 9Cannot parse date \"2020-03-03 00:00:00\": 
10while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null)) at [Source: (PushbackInputStream); 
11line: 1, column: 154] (through reference chain: com.kangaroohy.entity.bo.SearchBO[\"downDate\"])","path":"/api/search"}

因此,需要为 Feign 单独配置 FastJson,将原来的转换器替换成 FastJson 的,具体配置如下:

 1import com.alibaba.fastjson.serializer.SerializerFeature;
 2import com.alibaba.fastjson.support.config.FastJsonConfig;
 3import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
 4import feign.codec.Encoder;
 5import org.springframework.beans.factory.ObjectFactory;
 6import org.springframework.boot.autoconfigure.http.HttpMessageConverters;
 7import org.springframework.cloud.openfeign.support.SpringEncoder;
 8import org.springframework.context.annotation.Bean;
 9import org.springframework.context.annotation.Configuration;
10import org.springframework.http.MediaType;
11import org.springframework.http.converter.HttpMessageConverter;
12
13import java.util.ArrayList;
14import java.util.List;
15
16/**
17 * @desc: feign配置
18 * @author: kangaroohy
19 * @create: 2020/03/26
20 */
21@Configuration
22public class FeignClientConfig {
23
24    @Bean
25    public Encoder feignEncoder(){
26        return new SpringEncoder(feignHttpMessageConverter());
27    }
28
29    private ObjectFactory<HttpMessageConverters> feignHttpMessageConverter() {
30        final HttpMessageConverters httpMessageConverters = new HttpMessageConverters(createFastJsonConverter());
31        return () -> httpMessageConverters;
32    }
33
34    private HttpMessageConverter createFastJsonConverter(){
35        FastJsonHttpMessageConverter fastJsonConverter = new FastJsonHttpMessageConverter();
36        List<MediaType> supportedMediaTypes = new ArrayList<>();
37        supportedMediaTypes.add(MediaType.APPLICATION_JSON);
38        supportedMediaTypes.add(MediaType.APPLICATION_JSON_UTF8);
39        supportedMediaTypes.add(MediaType.APPLICATION_ATOM_XML);
40        supportedMediaTypes.add(MediaType.APPLICATION_FORM_URLENCODED);
41        supportedMediaTypes.add(MediaType.APPLICATION_OCTET_STREAM);
42        supportedMediaTypes.add(MediaType.APPLICATION_PDF);
43        supportedMediaTypes.add(MediaType.APPLICATION_RSS_XML);
44        supportedMediaTypes.add(MediaType.APPLICATION_XHTML_XML);
45        supportedMediaTypes.add(MediaType.APPLICATION_XML);
46        supportedMediaTypes.add(MediaType.IMAGE_GIF);
47        supportedMediaTypes.add(MediaType.IMAGE_JPEG);
48        supportedMediaTypes.add(MediaType.IMAGE_PNG);
49        supportedMediaTypes.add(MediaType.TEXT_EVENT_STREAM);
50        supportedMediaTypes.add(MediaType.TEXT_HTML);
51        supportedMediaTypes.add(MediaType.TEXT_MARKDOWN);
52        supportedMediaTypes.add(MediaType.TEXT_PLAIN);
53        supportedMediaTypes.add(MediaType.TEXT_XML);
54        fastJsonConverter.setSupportedMediaTypes(supportedMediaTypes);
55
56        FastJsonConfig fastJsonConfig = new FastJsonConfig();
57        fastJsonConfig.setSerializerFeatures(
58                // 是否输出值为null的字段,默认为false
59                SerializerFeature.WriteMapNullValue,
60                // 将Collection类型字段的字段空值输出为[]
61                SerializerFeature.WriteNullListAsEmpty,
62                // 将字符串类型字段的空值输出为空字符串
63                SerializerFeature.WriteNullStringAsEmpty,
64                // 将数值类型字段的空值输出为0
65                SerializerFeature.WriteNullNumberAsZero,
66                //Boolean字段如果为null,输出为false,而非null
67                SerializerFeature.WriteNullBooleanAsFalse,
68                //SerializerFeature.WriteDateUseDateFormat,
69                //枚举字段输出为枚举值
70                SerializerFeature.WriteEnumUsingToString,
71                // 禁用循环引用
72                SerializerFeature.DisableCircularReferenceDetect);
73
74        fastJsonConverter.setFastJsonConfig(fastJsonConfig);
75        return fastJsonConverter;
76    }
77}

此时,就不会发生上述的报错了。

特此记录。


标题:Spring Cloud Feign 配置 FastJson
作者:kangaroo1122
地址:https://kangaroohy.com/articles/2020/03/29/1585414815817.html
声明:如非特别说明,版权归kangaroo1122 所有,转载请注明出处,谢谢!
签名:No pains, no gains.