springcloud feign服务之间调用,date类型转换错误的问题
作者:l448797381
这篇文章主要介绍了springcloud feign服务之间调用,date类型转换错误的问题及解决,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
feign服务之间调用,date类型转换错误
最近尝试换springcloud开发,原先是springboot,每次的返回值的Date类型都通过@ControllerAdvice格式化yyyy-MM-dd HH:mm:ss然后返回的。这次用feign之后,2个服务之间调用,一直报错查了好久百度都搞不定,后面灵光一闪。。。不多说,上方案
自定义feign请求头
标识只有feign请求会多一个flag头
@Configuration public class FeignHeaderConfig implements RequestInterceptor { @Override public void apply(RequestTemplate requestTemplate) { ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder .getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); String token = request.getHeader(C.API_HEADER_PARAM_TOKEN); String session = request.getHeader(C.API_HEADER_PARAM_SESSION); String timestamp = request.getHeader(C.API_HEADER_PARAM_TIMESTAMP); requestTemplate.header(C.API_HEADER_PARAM_TOKEN, token); requestTemplate.header(C.API_HEADER_PARAM_SESSION,session); requestTemplate.header(C.API_HEADER_PARAM_TIMESTAMP,timestamp); requestTemplate.header("flag","feign");//标识feign请求 } }
通过判断是否为feign请求
再决定是否需要格式化时间
@ControllerAdvice @Slf4j public class RespondeBodyConfig implements ResponseBodyAdvice { @Override public Object beforeBodyWrite(Object resBody, MethodParameter arg1, MediaType arg2, Class arg3, ServerHttpRequest req, ServerHttpResponse res) { //解决feign之间调用格式化,导致date类型转换错误 List<String> flag = req.getHeaders().get("flag"); if(flag != null && flag.size() > 0 && flag.get(0).equals("feign")){ return resBody; } //resBody就是controller方法中返回的值,对其进行修改后再return就可以了 ObjectMapper mapper = new ObjectMapper(); SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss"); mapper.setDateFormat(format); try { if(resBody instanceof TResult) { String json = mapper.writeValueAsString(resBody); return JSONObject.parseObject(json, TResult.class); } } catch (Exception e) { log.error("【全局返回值处理失败】",e); } return resBody; } @Override public boolean supports(MethodParameter arg0, Class arg1) { //这里直接返回true,表示对任何handler的responsebody都调用beforeBodyWrite方法 return true; } }
openfeign服务间调用时日期格式异常
异常为
com.fasterxml.jackson.databind.exc.InvalidFormatException: Cannot deserialize value of type `java.util.Date` from String "2021-07-27 10:35:16": not a valid representation (error: Failed to parse Date value '2021-07-27 10:35:16': Cannot parse date "2021-07-27 10:35:16": while it seems to fit format 'yyyy-MM-dd'T'HH:mm:ss.SSSZ', parsing fails (leniency? null))
原因
使用OpenFeign进行服务间调用时返回的对象中时间类型为字符串型,接收的对象对应的类型为Date类型,openFeign转换日期格式时异常
解决方法
1.配置文件中加
spring.jackson.timeZone=GMT+08:00 spring.jackson.date-format=yyyy-MM-dd HH:mm:ss spring.jackson.serialization.write_dates_as_timestamps=false spring: jackson: timeZone: GMT+08:00 date-format: yyyy-MM-dd HH:mm:ss serialization.write_dates_as_timestamps: false
2、字段上加一下注解
@JsonFormat(pattern = "yyyy-MM-dd HH:mm:ss", timezone = "GMT+8") private Date createTime;
以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。