In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Internet Technology >
Share
Shulou(Shulou.com)06/02 Report--
This article mainly explains "how to close the Spring Boot application". The content in the article is simple and clear, and it is easy to learn and understand. Please follow the editor's train of thought to study and learn "how to close the Spring Boot application".
Preface
As online applications are gradually built using SpringBoot, there are more and more SpringBoot application instances. When an online application needs to be upgraded and deployed, the kill command is often used simply and rudely. This way of stopping the application will cause the application to discard all requests in processing and the response will fail. Such response failures, especially when dealing with important business logic, need to be avoided, so what better way to shut down SpringBoot applications smoothly? Let's explore it together through this article. (this article mainly focuses on the application of Spring Boot-based embedded Tomcat container as Web service.)
The sample code in this article can be obtained from the following warehouse address:
Springboot-shutdown: https://github.com/wrcj12138aaa/springboot-shutdown
Environmental support:
JDK 8
SpringBoot 2.1.4
Maven 3.6.0
Customize Tomcat Connector behavior
The premise of smoothly shutting down the Spring Boot application is to close its built-in Web container first and no longer process external incoming requests. In order to enable the application to accept shutdown event notifications and ensure that the current Tomcat handles all incoming requests, we need to implement the TomcatConnectorCustomizer API. The source code of this API is very simple. You can see from the comments that this is a callback API for implementing custom TomcatConnector behavior:
Here, if the partner is not familiar with Connector, I will briefly describe it: Connector belongs to the abstract component of Tomcat, and the function is to accept external requests, pass them internally, and return the response content. It is an important component of request processing and response in Tomcat. The specific implementations are HTTP Connector and AJP Connector.
By customizing the behavior of Connector, we can allow the Tomcat thread pool to be closed after the request has been processed, as shown in the following code:
The TIMEOUT variable defined in the above code is the maximum waiting time for the delayed shutdown of the Tomcat thread pool. Once this time is exceeded, the thread pool will be forced to close, and all requests cannot be processed. We can gracefully close the Web application by controlling the closing time of the Tomcat thread pool. It is also important to note that our class CustomShutdown implements the ApplicationListener interface, which means listening for events that the Spring container shuts down, that is, the current ApplicationContext executes the close method.
Embedded Tomcat to add Connector callback
With a custom Connector callback, we need to add it to the embedded Tomcat container during startup and wait for execution. So how is this step realized? you can refer to the following code:
Here TomcatServletWebServerFactory is the factory class of the Spring Boot implementation embedded in Tomcat, similar to other Web containers, there are also corresponding factory classes such as JettyServletWebServerFactory,UndertowServletWebServerFactory. Their common feature is that they inherit the same abstract class AbstractServletWebServerFactory and provide a default public implementation of the Web container, such as application context settings, session management and so on.
If we need to define a Tomcat container embedded in Spring Boot, we can use TomcatServletWebServerFactory to customize it. For example, a custom example is provided for the official document below:
All right, back to the point, we use the addConnectorCustomizers method to add the custom Connector behavior to the embedded Tomcat. In order to see the loading effect, we can get the webServerFactory object from the container after the Spring Boot program starts, and then observe that we can see that the CustomeShutdown object already exists in its tomcatConnectorCustomizers property.
Turn on Shutdown Endpoint
So far, the operation to make the embedded Tomcat container close smoothly has been completed. The next thing to do is how to close the Spring container actively. In addition to the regular Linux command Kill, we can use Spring Boot Actuator to achieve the remote closure of the Spring container. How to continue to see
Spring Boot Actuator is a major feature of Spring Boot, which provides rich functions to help us monitor and manage Spring Boot applications running in a production environment. We can manage our application through HTTP or JMX. In addition, it provides the functions of audit, health status and measurement information collection for our application, which can help us to understand the running application more comprehensively.
Actuator, ['æ kt brakes'e brake t] translated into Chinese means a brake, a manufacturing term that refers to a mechanism used to control something.
Spring Boot Actuator also provides the feature to control the closure of applications, so we need to introduce Spring Boot Actuator for applications by adding the corresponding starter dependencies to the current project, taking the Maven project as an example:
Spring Boot Actuator exposes Endpoint (endpoints) to the outside to allow us to monitor and manage with the application. After introducing spring-boot-starter-actuator, we need to enable the Shutdown Endpoint we need. In the configuration file application.properties, set as follows
The first line indicates that Shutdown Endpoint is enabled, and the second line indicates that all Endpoint is exposed as HTTP to the outside, and all Endpoint except Shutdown Endpoint is enabled by default.
There are more than ten kinds of Shutdown Endpoint,Actuator Endpoint, some of which are specific operations, such as heapdump dump memory log, and some are information display, such as health showing the health status of the application. For all the Endpoint information, please refer to the official document-53. Endpoints section.
At this point, our preliminary configuration work is complete. When you start the application, you can request the http://host:port/actuator/shutdown of the corresponding path through POST to achieve the remote shutdown of the Spring Boot application. Is it very simple?
Simulation test
Here, in order to simulate the test, we first simulate the request controller BusinessController that processes business for up to 10 seconds. The specific implementation is as follows:
Use Thread.sleep to block the current request thread and simulate business processing, and at the same time access Shutdown Endpoint in HTTP mode to try to close the application. You can actually close the application by observing the console log to see whether the application will complete the processing of the request.
First, use the curl command to simulate sending a business request:
Then, in the business processing, send the request actuator/shutdown directly to try to shut down the application, using the same curl method:
The response result will be returned immediately after the actuator/shutdown request is sent, but the application will not stop:
Finally, take a look at the log output order of the console:
You can see that sending a request to close the application immediately after sending the business request will not stop the application immediately, but after the request is processed, the application begins to exit after 10 seconds of blocking, which ensures that the received request will return to the normal response, and the request that enters after closing the request will not be processed. Here, we gracefully close the Spring Boot program.
Realize automation
Because Spring Boot provides the convenience of embedded Web containers, we often package programs into jar and release them. Usually, the operation process of startup and shutdown of applications is fixed and repetitive. In accordance with the principle of Don't Repeat Yourself, it is necessary to automate this operation process and write shell scripts for the operations of closed and enabled SpringBoot applications, so as to avoid human errors, facilitate use and improve operation efficiency. The following is the program startup script I wrote for the sample program: (the specific script can be seen in the sample project)
With the script, we can smoothly update and deploy the Spring Boot program directly from the command line, with the following effect:
Thank you for your reading, the above is the content of "how to close the Spring Boot application", after the study of this article, I believe you have a deeper understanding of how to close the Spring Boot application, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.