繁体   English   中英

如何让 Springboot 的 ShutdownHook 等待,直到它的所有处理请求都完成?

[英]How to make the Springboot's ShutdownHook wait, till all of its processing requests are completed?

I am running my Spring boot web application inside the docker container and every time we safely stop the container, it abruptly shut down the running spring-boot service(Default behavior). 我的要求是处理现有请求没有任何问题。 我已经尝试了以下方法,例如在ContextClosedEvent中添加睡眠逻辑几分钟,以便现有请求有时间提供响应,但是即使在启动关闭之后,以下方法也不会停止传入的请求。 有什么具体方法可以满足我的要求吗?

@Slf4j
@SpringBootApplication
public class Application {

    public static void main(String[] args) {
        SpringApplication application = new SpringApplication(Application.class);
        application.addListeners((ApplicationListener<ContextClosedEvent>) event -> {
            log.info("Shutdown initiated...");
            try {
                Thread.sleep(TimeUnit.MINUTES.toMillis(5));
            } catch (InterruptedException e) {
                log.error("Exception is thrown", e);
            }
            log.info("Graceful Shutdown is processed succesfully");
        });
        application.run(args);
    }

分享我的方法。 假设您将 Springboot 应用程序用作 web 应用程序,并且您希望处理现有请求而不突然终止它们,spring 引导提供了开箱即用的解决方案。

Spring 文档的摘录

所有四个嵌入式 web 服务器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反应式和基于 Servlet 的 Z2567A5EC9705EB7AC2C984033E0618 应用程序都支持正常关闭。 它作为关闭应用程序上下文的一部分发生,并在停止 SmartLifecycle bean 的最早阶段执行。 此停止处理使用超时提供宽限期,在此期间将允许完成现有请求,但不允许新请求。 不允许新请求的确切方式取决于正在使用的 web 服务器。 Jetty、Reactor Netty 和 Tomcat 将停止接受网络层的请求。 Undertow 将接受请求,但会立即以服务不可用 (503) 响应进行响应。

注意:使用 Tomcat 正常关机需要Tomcat 9.0.33 or later

代码片段

启用正常关机

server.shutdown=graceful

配置超时时间(这里我将时间值设置为1分钟)

spring.lifecycle.timeout-per-shutdown-phase=1m

控制台 output:

[INFO] [SpringContextShutdownHook] [org.springframework.boot.web.embedded.tomcat.GracefulShutdown:53] Comme
ncing graceful shutdown. Waiting for active requests to complete

...logs of existing running API endpoints

[tomcat-shutdown]   [org.springframework.boot.web.embedded.tomcat.GracefulShutdown:78] Graceful shut
down complete
[SpringContextShutdownHook] [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor:218] S
hutting down ExecutorService 'applicationTaskExecutor'

从上面的日志中,你可以看到 spring 启动等待所有正在运行的请求处理并优雅地关闭服务器

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM