SoFunction
Updated on 2025-04-14

One article will help you understand how springBoot can achieve elegant shutdown

In distributed systems, the Graceful Shutdown of services is an important mechanism to ensure business continuity. Spring Boot ByEmbed server supportandLifecycle ManagementThis function has been implemented, the following are the specific implementation methods and configuration details:

1. The core goal of elegant downtime

  • Stop receiving new requests: Close the listening port and no longer accept new connections.
  • Waiting for processing request to complete: Allows the executing request to continue processing until timeout.
  • Release resources: Close database connection pool, thread pool and other resources.
  • Avoid data inconsistency: Ensure transaction integrity and prevent interruptions from going through.

2. Elegant downtime configuration based on embedded servers

Starting from version 2.3, Spring Boot has built-in elegant downtime support for embedded servers such as Tomcat, Jetty, and Undertow.

2.1 Enable elegant shutdown

existorConfiguration in:

server:
  shutdown: graceful  # Enable elegant shutdown modespring:
  lifecycle:
    timeout-per-shutdown-phase: 30s  # Timeout time to wait for the request to complete (default 30 seconds)

2.2 Behavior of different servers

server Elegant downtime behavior
Tomcat Stop receiving new requests, wait for the processing request to complete, and force close after the timeout.
Jetty Stop receiving new connections and wait for the active request to complete.
Undertow Close the listening port and wait for the active request to complete.

2.3 Verify downtime process

1. Send a shutdown signal

passSIGTERMSignal (Kill command) or Actuator endpoint closes the application.

Using Actuator endpoints requires adding dependencies and configuration:

<dependency>
    <groupId></groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
management:
  endpoint:
    shutdown:
      enabled: true
  endpoints:
    web:
      exposure:
        include: shutdown

Send a POST request to close the application:

curl -X POST http://localhost:8080/actuator/shutdown

2. Observe the log

2023-10-05 14:20:00 INFO   : Commencing graceful shutdown. Waiting for active requests to complete
2023-10-05 14:20:30 INFO   : Graceful shutdown complete

3. Custom downtime logic extension

3.1 Listening for downtime events

By implementingApplicationListener<ContextClosedEvent>Listen to the context shutdown event:

@Component
public class GracefulShutdownListener implements ApplicationListener&lt;ContextClosedEvent&gt; {
    @Override
    public void onApplicationEvent(ContextClosedEvent event) {
        //dubbo close        ().stop();
        // Execute custom cleanup logic (such as closing thread pool and freeing resources)        ExecutorService executor = ().getBean();
        ();
        try {
            if (!(30, )) {
                ();
            }
        } catch (InterruptedException e) {
            ().interrupt();
        }
    }
}

3.2 Annotation with @PreDestroy

Perform cleaning logic before bean destruction:

@Service
public class DatabaseService {
    @PreDestroy
    public void cleanup() {
        // Close the database connection        DataSource dataSource = ...;
        ();
    }
}

4. Elegant downtime for integrated Kubernetes

In Kubernetes, combine Pod lifecycle hooks to achieve elegant downtime:

4.1 Configuring PreStop Hook

Add in Deployment configurationpreStopHook, delayed termination of process:

spec:
  template:
    spec:
      containers:
        - name: app
          lifecycle:
            preStop:
              exec:
                command: ["sh", "-c", "sleep 30"]  # Wait for 30 seconds before sending SIGTERM          terminationGracePeriodSeconds: 60  # Total grace period (including preStop)

4.2 Cooperate with ready probes

Tagging service is not available before shutdown:

readinessProbe:
  httpGet:
    path: /actuator/health/readiness
    port: 8080

5. FAQs and Solutions

question Solution
There are still unfinished requests after downtime Adjust -per-shutdown-phase to extend the waiting time.
Thread pool task not completed Customize the ExecutorService and call shutdown() and awaitTermination() on downtime.
Database connection not closed Explicitly close the connection pool via @PreDestroy or DisposableBean.
Kubernetes Forced Termination of Pod Make sure that terminationGracePeriodSeconds is greater than the elegant downtime timeout.

6. Verify the elegant shutdown effect

1. Send long time-consuming requests

curl http://localhost:8080/long-task

2. Trigger shutdown

curl -X POST http://localhost:8080/actuator/shutdown

3. Observation results

  • New request returns503 Service Unavailable
  • The request being processed continues to execute until it is completed or timed out.

Summarize

passEmbed server configurationLife cycle hookandKubernetes Integration, Spring Boot implements elegant downtime out of the box. Key configurations include:

  • Enable =graceful.
  • Set a reasonable timeout.
  • Combined with Actuator endpoints or Kubernetes lifecycle management.

This is the article about this article about how springBoot can achieve elegant shutdown. For more related springBoot content, please search for my previous article or continue browsing the related articles below. I hope everyone will support me in the future!