如何优雅地停止 Spring Boot 应用?

  首先来介绍下什么是优雅地停止,简而言之,就是对应用进程发送停止指令之后,能保证正在执行的业务操作不受影响,可以继续完成已有请求的处理,但是停止接受新请求

  我们很多时候都需要安全的将服务停止,也就是把没有处理完的工作继续处理完成。比如停止一些依赖的服务,输出一些日志,发一些信号给其他的应用系统,这个在保证系统的高可用是非常有必要的。

   在 Spring Boot 2.3.0.RELEASE中增加了新特性优雅停止,目前 Spring Boot 内置的四个嵌入式 Web 服务器(Jetty、Reactor Netty、Tomcat 和 Undertow)以及反应式和基于 Servlet 的 Web 应用程序都支持优雅停止。

步骤:

  •   Step1:首先创建一个 Spring Boot 的 Web 项目,版本选择 2.3.0.RELEASE,Spring Boot2.3.0.RELEASE 版本内置的 Tomcat 为 9.0.35

  •   Step2:在pom.xml中添加如下actuator组件。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
  •   Step3:在springboot的全局配置文件application.yml 中添加配置。
server:
  shutdown: graceful  #启用graceful shutdown来停止Web容器,默认的是Immediate shutdown。
management:
  endpoint:
    shutdown:
      enabled: true   #启用以暴露actuator的shutdown接口
  endpoints:
    web:
      exposure:       
        include: "*"
      base-path: /myactuator  #自定义管理端点的前缀(保证安全)防止别人知道你的ip和端口

其中,平滑关闭内置 Web 容器(以 Tomcat 为例)的入口代码在 org.springframework.boot.web.embedded.tomcatGracefulShutdown 里,大概逻辑就是先停止外部的所有新请求,然后再处理关闭前收到的请求。

内嵌的 Tomcat 容器平滑关闭的配置已经完成了,那么如何优雅关闭 Spring 容器了,就需要Step2中的actuator 组件来实现 Spring 容器的优雅关闭。通过 Actuator 关闭 Spring 容器的入口代码在 org.springframework.boot.actuate.context 包下 ShutdownEndpoint 类中,主要的就是执行 doClose() 方法关闭并销毁 applicationContext

  •   Step4: 在springboot的启动函数类中添加tomcat的的停机支持。(在2.3.0版本以前需要这一步,之后就不需要添加tomcat支持了,因为前面已经配置了)
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
/**
 * ----------------------------------------------------------------------
 * @Desc: SpringBoot启动类  (SpringBoot 2.3.0版本之后不需要添加Tomcat支持)
 * @author Create by Liu Wen at 2020/6/16 22:20
 * ----------------------------------------------------------------------
 */
@SpringBootApplication
public class GracefulApplication implements CommandLineRunner {
    
	public static void main(String[] args) {
		SpringApplication.run(GracefulApplication.class, args);
	}
import lombok.extern.slf4j.Slf4j;
import org.apache.catalina.connector.Connector;
import org.springframework.boot.SpringApplication;

import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;
import org.springframework.boot.web.embedded.tomcat.TomcatServletWebServerFactory;
import org.springframework.boot.web.servlet.server.ServletWebServerFactory;
import org.springframework.context.ApplicationListener;
import org.springframework.context.annotation.Bean;
import org.springframework.context.event.ContextClosedEvent;

import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
/**
 * ----------------------------------------------------------------------
 * @Desc: SpringBoot启动类    SpringBoot 2.3.0版本之前需要添加Tomcat支持
 * @author Create by Liu Wen at 2020/6/16 22:21
 * ----------------------------------------------------------------------
 */
@SpringBootApplication
@Slf4j
public class GracefulApplication implements CommandLineRunner {
    
	public static void main(String[] args) {
		SpringApplication.run(GracefulApplication.class, args);
	}
	/**
	 *用于监听shutdown 事件
	 */
	@Bean
	public GracefulShutdown gracefulShutdown() {
		return new GracefulShutdown();
	}

	@Bean
	public ServletWebServerFactory servletContainer() {
		TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory();
		tomcatServletWebServerFactory.addConnectorCustomizers(gracefulShutdown());
		return tomcatServletWebServerFactory;
	}

	private class GracefulShutdown implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> {
		private volatile Connector connector;
		private final int waitTime = 10;

		@Override
		public void customize(Connector connector) {
			this.connector = connector;
		}

		@Override
		public void onApplicationEvent(ContextClosedEvent contextClosedEvent) {
			this.connector.pause();
			Executor executor = this.connector.getProtocolHandler().getExecutor();
			try {
				if (executor instanceof ThreadPoolExecutor) {
					ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
					threadPoolExecutor.shutdown();
					if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {

					}
				}
			} catch (Exception e) {
				e.printStackTrace();
				Thread.currentThread().interrupt();
			}
		}
	}


}
  • Step5:在 controller 包下创建一个GracefulController 类,并有一个 work 方法,用来模拟复杂业务耗时处理流程,具体代码如下。
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;
/**
 * @description: 测试SpringBoot优雅的启动
 * @author: Create by Liu Wen at 2020-06-16 22:22
 **/
@RestController
public class GracefulController {
    @GetMapping("/work")
    public String work() throws InterruptedException {
        // 模拟复杂业务耗时处理流程
        Thread.sleep(10 * 1000L);
        return "Success";
    }
}

  • Step6:测试,启动项目,先用 Postman 发送第一个请求 http://localhost:8080/work 处理业务。

  • 然后在这个时候,调用 http://localhost:8080/myactuator/shutdown (记住这里是Post请求)就可以执行优雅地停止,返回结果如下:

    {
        "message": "Shutting down, bye..."
    }
    
  • 如果在这个时候,发起另一个请求 http://localhost:8080/work,则会没有反应。而第一个请求返回:Success。运行日志有几行如下:

    2020-06-16 23:05:15.163  INFO 102724 --- [     Thread-253] o.s.b.w.e.tomcat.GracefulShutdown        : Commencing graceful shutdown. Waiting for active requests to complete
    2020-06-16 23:05:15.287  INFO 102724 --- [tomcat-shutdown] o.s.b.w.e.tomcat.GracefulShutdown        : Graceful shutdown complete
    2020-06-16 23:05:15.295  INFO 102724 --- [     Thread-253] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
    

    从日志中也可以看出来,当调用 shutdown 接口的时候,会先等待请求处理完毕后再优雅地停止。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

进击的程序猿~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值