What's new: how can Spring Boot 2.3.0 stop gracefully?

Original text: https://mp.weixin.qq.com/s/uvNkdcmwkd6lcSRDhjPUJQ


1. What is elegant shutdown

Let's start with a simple piece of code,As follows:

public class DemoController {
 public String demo() throws InterruptedException {
     //Simulate the time-consuming process of business
  Thread.sleep(20 * 1000L);
  return "hello";

When we request traffic to execute business logic on this interface,If the server performs a kill at this time,By default, spring boot will directly close the container (tomcat, etc.),Cause this business logic execution to fail. In some business scenarios, data inconsistency may occur,Transaction logic is not rolled back.

2.graceful shutdown

In the latest spring boot version 2.3,Built in,It does not need to expand the container thread pool for processing,At present, the web servers (Jetty, Reactor Netty, Tomcat and undercow) and reactive and Servlet based web applications supported by spring boot embedded support elegant downtime. Let's look at how to use:

When using server.shutdown=graceful When enabled,When the web container is closed,The web server will no longer receive new requests,And will wait for the buffer period for the completion of the active request.

3. Configuration experience



The shutdown behavior supported here,Let's see the following source code enumeration:

 * Configuration for shutting down a {@link WebServer}.
 * @author Andy Wilkinson
 * @since 2.3.0
public enum Shutdown {
  * Elegant shutdown (deadline shutdown)

  * Stop immediately


Buffer period timeout per shutdown phase configuration




4. Relevant knowledge

4.1 execute kill-2 instead of kill-9 here
 public void registerShutdownHook() {
  if (this.shutdownHook == null) {
   // No shutdown hook registered yet.
   this.shutdownHook = new Thread(SHUTDOWN_HOOK_THREAD_NAME) {
    public void run() {
     synchronized (startupShutdownMonitor) {

4.2 Elegant downtime via actor endpoint

POST requests / Actor / shutdown to perform an elegant shutdown.

Source code analysis

@Endpoint(id = "shutdown", enableByDefault = false)
public class ShutdownEndpoint implements ApplicationContextAware {

 public Map<String, String> shutdown() {
  Thread thread = new Thread(this::performShutdown);

 private void performShutdown() {
  try {
  catch (InterruptedException ex) {

  //The close logic here is the same as the shutdown hook above

4.3 The difference of graceful downtime behavior between different web containers

Container downtime behavior depends on the specific web container behavior


Tags: Spring Tomcat Jetty Netty

Posted on Sun, 24 May 2020 06:27:31 -0400 by thebopps