最近在网上查找关于SpringBoot设置接口超时时间的问题,大部分都是三种方式:
1、在配置文件application.properties中加了spring.mvc.async.request-timeout=20000,意思是设置超时时间为20000ms即20s;
2、重写WebMvcConfigurerAdapter 的configureAsyncSupport方法;
3、使用RestTemplate超时,设置配置HttpComponentsClientHttpRequestFactory中的RequestConfig属性;
按照上面三种方式进行设置,测试均没有生效,于是继续查找资料,终于在 https://stackoverflow.com/questions/34852236/spring-boot-rest-api-request-timeout 中找到了答案。
首先,我们需要在配置文件application.properties中添加
spring.mvc.async.request-timeout=20000
单纯添加配置文件是不够的,要想使配置生效,还需要返回Callable<>,代码如下
@RequestMapping(method = RequestMethod.GET)
public Callable<String> getFoobar() throws InterruptedException {
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(8000); //this will cause a timeout
return "foobar";
}
};
}
最终,经过测试,此方式有效,在请求超过设置的超时时间后,tomcat会返回500,
对于最开始提到的另外两种方式,没有做进一步研究,不能完全否认,也有可能是我在测试的时候某些地方处理的不对。
https://stackoverflow.com/questions/34852236/spring-boot-rest-api-request-timeout