Spring Boot 设置 Controller 处理超时时间
Spring Boot Tomcat About 2,766 words同步接口
对于同步接口,Spring Boot
并不支持服务端的超时时间。(即:客户端不中断请求的情况下将无限制等待服务端返回信息)
而server.tomcat.connection-timeout
的连接超时是指三次握手的建立连接时的超时,并发针对接口中业务处理超长时间的超时限制。
异步接口
使用Callable
异步返回结果。
@GetMapping("/timeout")
public Callable<String> timeout() {
System.out.println(LocalDateTime.now() + ": 超长处理, threadId: " + Thread.currentThread().getId());
return () -> {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println(LocalDateTime.now() + ": 继续执行, threadId: " + Thread.currentThread().getId());
return "timeout";
};
}
可以发现30
秒后,中断了sleep
。
2023-07-14T10:18:36.543868: 超长处理, threadId: 28
java.lang.InterruptedException: sleep interrupted
at java.base/java.lang.Thread.sleep(Native Method)
at TestController.lambda$timeout$0(AuthController.java:39)
at org.springframework.web.context.request.async.WebAsyncManager.lambda$startCallableProcessing$4(WebAsyncManager.java:337)
at java.base/java.util.concurrent.Executors$RunnableAdapter.call(Executors.java:515)
at java.base/java.util.concurrent.FutureTask.run(FutureTask.java:264)
at java.base/java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1128)
at java.base/java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:628)
at java.base/java.lang.Thread.run(Thread.java:829)
2023-07-14T10:19:07.341425: 继续执行, threadId: 51
2023-07-14 10:19:07.357 WARN 61586 --- [nio-8081-exec-2] .w.s.m.s.DefaultHandlerExceptionResolver : Resolved [org.springframework.web.context.request.async.AsyncRequestTimeoutException]
返回的HTTP
状态码为503
。
❯ curl -vv http://localhost:8081/timeout
* Trying 127.0.0.1:8081...
* Connected to localhost (127.0.0.1) port 8081 (#0)
> GET /timeout HTTP/1.1
> Host: localhost:8081
> User-Agent: curl/7.88.1
> Accept: */*
>
< HTTP/1.1 503
< Cache-Control: private
< Content-Type: text/html;charset=utf-8
< Content-Language: en
< Content-Length: 451
< Date: Fri, 14 Jul 2023 02:23:23 GMT
< Connection: close
<
* Closing connection 0
<!doctype html><html lang="en"><head><title>HTTP Status 503 – Service Unavailable</title><style type="text/css">body {font-family:Tahoma,Arial,sans-serif;} h1, h2, h3, b {color:white;background-color:#525D76;} h1 {font-size:22px;} h2 {font-size:16px;} h3 {font-size:14px;} p {font-size:12px;} a {color:black;} .line {height:1px;background-color:#525D76;border:none;}</style></head><body><h1>HTTP Status 503 – Service Unavailable</h1></body></html>%
可以设置异步接口的超时时间,默认是30
秒。
spring:
mvc:
async:
request-timeout: 5s
代理
对于Spring Boot
上游有一层代理的情况下(如Nginx
代理),可以设置Nginx
的代理超时时间。
Views: 2,668 · Posted: 2023-07-17
————        END        ————
Give me a Star, Thanks:)
https://github.com/fendoudebb/LiteNote扫描下方二维码关注公众号和小程序↓↓↓
Loading...