Web Server Graceful Shutdown in Spring Boot – Spring Boot中的Web服务器优雅关机

最后修改: 2020年 8月 23日

中文/混合/英文(键盘快捷键:t)

1. Overview

1.概述

In this quick tutorial, we’re going to see how we can configure Spring Boot applications to handle shutdowns more gracefully.

在这个快速教程中,我们将看到如何配置Spring Boot应用程序以更优雅地处理关机。

2. Graceful Shutdown

2.优雅关机

As of Spring Boot 2.3, Spring Boot now supports the graceful shutdown feature for all four embedded web servers (Tomcat, Jetty, Undertow, and Netty) on both servlet and reactive platforms.

Spring Boot 2.3开始,Spring Boot现在支持所有四个嵌入式Web服务器(Tomcat、Jetty、Undertow和Netty)在Servlet和反应式平台上的优雅关闭功能。

To enable the graceful shutdown, all we have to do is to set the server.shutdown property to graceful in our application.properties file:

为了启用优雅关机,我们所要做的就是在我们的application.properties文件中把server.shutdown属性设置为graceful

server.shutdown=graceful

Then, Tomcat, Netty, and Jetty will stop accepting new requests at the network layer. Undertow, on the other hand, will continue to accept new requests but send an immediate 503 Service Unavailable response to the clients.

然后,Tomcat、Netty和Jetty将停止接受网络层的新请求。另一方面,Undertow将继续接受新的请求,但立即向客户发送503服务不可用的响应。

By default, the value of this property is equal to immediate, which means the server gets shut down immediately.

默认情况下,该属性的值等于immediate,这意味着服务器被立即关闭。

Some requests might get accepted just before the graceful shutdown phase begins. In that case, the server will wait for those active requests to finish their work up to a specified amount of time. We can configure this grace period using the spring.lifecycle.timeout-per-shutdown-phase configuration property:

有些请求可能会在优雅关闭阶段开始前被接受。在这种情况下,t服务器将等待这些活动的请求完成它们的工作,直到指定的时间为止。我们可以使用spring.lifecycle.timeout-per-shutdown-phase配置属性来配置这个宽限期。

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

If we add this, the server will wait up to one minute for active requests to complete. The default value for this property is 30 seconds.

如果我们添加这个,服务器将等待最多一分钟来完成活动请求。这个属性的默认值是30秒。

3. Conclusion

3.总结

In this short tutorial, we saw how we could take advantage of the new graceful shutdown feature in Spring Boot 2.3.

在这个简短的教程中,我们看到了如何利用Spring Boot 2.3中新的优雅关机功能。