Spring Boot 內嵌容器 Tomcat / Undertow

m53469發表於2021-09-09

Spring Boot 在關閉時,如果有請求沒有響應完,在不同的容器會出現不同的結果,例如,在 Tomcat 和 Undertow 中會出現中斷異常,那麼就有可能對業務造成影響。所以,優雅停機非常有必要性,目前官方是沒有提供很好的策略來實現。

Each SpringApplication registers a shutdown hook with the JVM to ensure that the ApplicationContext closes gracefully on exit. All the standard Spring lifecycle callbacks (such as the DisposableBean interface or the @PreDestroy annotation) can be used.

Spring Boot Application 在接收到停機訊號後,可以透過  DisposableBean 介面 、 @PreDestroy 註解 或者 ContextClosedEvent 事件來處理優雅停機的相關邏輯。

版本資訊

Spring Boot 版本: 2.0.0.RELEASE

Tomcat 優雅停機

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }    /**
     * 用於接受 shutdown 事件
     */
    @Bean
    public GracefulShutdown gracefulShutdown() {        return new GracefulShutdown();
    }    @Bean
    public ServletWebServerFactory servletContainer() {
        TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();
        tomcat.addConnectorCustomizers(gracefulShutdown());        return tomcat;
    }    /**
     * 優雅關閉 Spring Boot
     */
    private class GracefulShutdown implements TomcatConnectorCustomizer, ApplicationListener {        private final Logger log = LoggerFactory.getLogger(GracefulShutdown.class);        private volatile Connector connector;        private final int waitTime = 30;        @Override
        public void customize(Connector connector) {            this.connector = connector;
        }        @Override
        public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {            this.connector.pause();
            Executor executor = this.connector.getProtocolHandler().getExecutor();            if (executor instanceof ThreadPoolExecutor) {                try {
                    ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
                    threadPoolExecutor.shutdown();                    if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {
                        log.warn("Tomcat thread pool did not shut down gracefully within " + waitTime + " seconds. Proceeding with forceful shutdown");
                    }
                } catch (InterruptedException ex) {
                    Thread.currentThread().interrupt();
                }
            }
        }
    }

}

Undertow 優雅停機

@SpringBootApplicationpublic class Application {    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }    /**
     * 優雅關閉 Spring Boot
     */
    @Component
    public class GracefulShutdown implements ApplicationListener {        @Autowired
        private GracefulShutdownWrapper gracefulShutdownWrapper;        @Autowired
        private ServletWebServerApplicationContext context;        @Override
        public void onApplicationEvent(ContextClosedEvent contextClosedEvent){
            gracefulShutdownWrapper.getGracefulShutdownHandler().shutdown();            try {
                UndertowServletWebServer webServer = (UndertowServletWebServer)context.getWebServer();
                Field field = webServer.getClass().getDeclaredField("undertow");
                field.setAccessible(true);
                Undertow undertow = (Undertow) field.get(webServer);
                List listenerInfo = undertow.getListenerInfo();
                Undertow.ListenerInfo listener = listenerInfo.get(0);
                ConnectorStatistics connectorStatistics = listener.getConnectorStatistics();                while (connectorStatistics.getActiveConnections() > 0){}
            }catch (Exception e){                // Application Shutdown
            }
        }
    }
}
@Componentpublic class GracefulShutdownWrapper implements HandlerWrapper{    private GracefulShutdownHandler gracefulShutdownHandler;    @Override
    public HttpHandler wrap(HttpHandler handler) {        if(gracefulShutdownHandler == null) {            this.gracefulShutdownHandler = new GracefulShutdownHandler(handler);
        }        return gracefulShutdownHandler;
    }    public GracefulShutdownHandler getGracefulShutdownHandler() {        return gracefulShutdownHandler;
    }

}
@Component@AllArgsConstructorpublic class UndertowExtraConfiguration {    private final GracefulShutdownWrapper gracefulShutdownWrapper;    @Bean
    public UndertowServletWebServerFactory servletWebServerFactory() {
        UndertowServletWebServerFactory factory = new UndertowServletWebServerFactory();
        factory.addDeploymentInfoCustomizers(deploymentInfo -> deploymentInfo.addOuterHandlerChainWrapper(gracefulShutdownWrapper));
        factory.addBuilderCustomizers(builder -> builder.setServerOption(UndertowOptions.ENABLE_STATISTICS, true));        return factory;
    }

}

Jetty 優雅停機

預設支援所有請求完畢後再關閉,缺點:客戶端接收不到響應,有待改進!

相關內容


作者:Anoyi
連結:


來自 “ ITPUB部落格 ” ,連結:http://blog.itpub.net/2819/viewspace-2802432/,如需轉載,請註明出處,否則將追究法律責任。

相關文章