现象:接口默认1min超时,超过时间直接504
考虑到业务,存在超级慢的接口,需要调大超时时间。网上一搜…一言难尽… 大部分文章都提到以下两个配置spring.mvc.async.request-timeout和server.tomcat.connection-timeout,但实测,不能达到效果。
最终想到接口经过nginx转发,在nginx中加了proxy_read_timeout配置后实现效果。
location /xxx {
root html;
proxy_pass http://172.26.1.1:8888;
index index.html index.htm;
proxy_read_timeout 150; # 此行生效
}
考虑spring/tomcat本身是否有相关配置,翻阅了官方文档和源码,最终得到结论:
- 对于同步接口,暂时没有(没找到)超时时间配置。
- 对于异步接口,有超时时间配置(具体往下看spring.mvc.async.request-timeout)。
下方列了两个大部分文章都提到的配置项描述、使用方式,以及其他超时时间配置方法:
server.tomcat.connection-timeout
Amount of time the connector will wait, after accepting a connection, for the request URI line to be presented.
引用[1]
按照我的理解,server.tomcat.connection-timeout是建立连接需要的时间,非连接处理的时间
spring.mvc.async.request-timeout
Amount of time before asynchronous request handling times out. If this value is not set, the default timeout of the underlying implementation is used.
引用[2]
异步请求的时间,搭配Callable使用,示例如下:
@GetMapping("/test")
public Callable<String> test(){
return new Callable<String>() {
@Override
public String call() throws Exception {
Thread.sleep(30000); //this will cause a timeout
return "test";
}
};
}
spring.mvc.async.request-timeout 也可以使用代码配置,如下:
@Component
public class MyTomcatWebServerFactoryCustomizer implements WebServerFactoryCustomizer<TomcatServletWebServerFactory> {
@Override
public void customize(TomcatServletWebServerFactory server) {
server.addConnectorCustomizers((connector) -> connector.setAsyncTimeout(Duration.ofSeconds(20).toMillis()));
}
}
其他方案
过滤器/拦截器代码处理
[1] spring源码 https://github.com/spring-projects/spring-boot/blob/main/spring-boot-project/spring-boot-autoconfigure/src/main/java/org/springframework/boot/autoconfigure/web/ServerProperties.java
[2] spring官方文档 https://docs.spring.io/spring-boot/docs/current-SNAPSHOT/reference/htmlsingle/#web