一:背景
项目需求查询某天之前的所有数据,使用A服务Feign调用B服务,date做参数,发现请求到B服务之后date参数多了14个小时。
@GetMapping("/query")
public Response query(@RequestParam(name = "sendTimeEnd") Date sendTimeEnd);
二:探索
经多方查证,发现feign处理参数的时候会调用new Date(sendTimeEnd.toString)方法,该方法已弃用,方法上有一段注释,建议用DateFormat.parse代替new Date() 。
replaced by <code>DateFormat.parse(String s)</code>.
public static void main(String[] args) throws ParseException {
Date date = new Date();
Date date1 = new Date(date.toString());
System.out.println(date); // Mon Nov 28 17:15:34 CST 2022
System.out.println(date1); // Tue Nov 29 07:15:34 CST 2022
}
三:解决方案
1. 同时修改A服务和B服务,A服务date参数改为long类型,B服务date参数改为long类型。这样就不会遇到时差问题。
2.A服务添加feign处理类
@Configuration
public class FeignDateFormatRegister implements FeignFormatterRegistrar {
@Override
public void registerFormatters(FormatterRegistry registry) {
registry.addFormatter(dateFormatter());
}
@Bean
public DateFormatter dateFormatter() {
return new DateFormatter("yyyy-MM-dd HH:mm:ss.SSS");
}
}
B服务接收参数加@DateTimeFormat注解。
@DateTimeFormat(pattern="yyyy-MM-dd HH:mm:ss.SSS")
private Date sendTimeEnd;