赞
踩
服务优雅停机分运维层面和应用层面,在这里主要讲一下应用层面的优雅停机,这里讲到的实现方式和案例均是在springboot项目下。
springboot支持应用的优雅停机,当应用接收到kill的信号(15 终止号令)时,会停止接收新的请求,并等待活跃的请求完成后,关闭服务,通过yml文件配置:
server:
shutdown: graceful //IMMEDIATE立即停机(默认值)、GRACEFUL
shutdown配置介绍:
GRACEFUL:should support graceful shutdown, allowing active requests time to complete.
IMMEDIATE:should shut down immediately.
但是需要注意的事,该种方式只对web请求所产生的线程有效,应用内新建立的线程无效(只要活跃的请求完成,即使应用内有线程存活,依然会立即关闭)。
优雅停机效果同springboot2.3.1.
@Component @Slf4j public class GracefulShutdownTomcat implements TomcatConnectorCustomizer, ApplicationListener<ContextClosedEvent> { private volatile Connector connector; private final int waitTime = 30; @Override public void customize(Connector connector) { this.connector = connector; } @Override public void onApplicationEvent(ContextClosedEvent event) { this.connector.pause(); log.info("active Thread count: {}", Thread.activeCount()); Executor executor = this.connector.getProtocolHandler().getExecutor(); if (executor instanceof ThreadPoolExecutor) { ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor)executor; threadPoolExecutor.shutdown(); try { if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) { log.warn("Tomcat thread pool did't shut down gracefully within" + waitTime + " seconds. Proceeding with forceful shutdown"); } } catch (InterruptedException e) { Thread.currentThread().interrupt(); } } } @Bean public ConfigurableServletWebServerFactory servletContainer(final GracefulShutdownTomcat gracefulShutdownTomcat) { TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory(); tomcat.addConnectorCustomizers(gracefulShutdownTomcat); return tomcat; } }
通过jvm的钩子监控kill信号,该种方式对应用内建立的线程池有效(会在设定的最大等待时间达到之前,一直等待线程执行完成,或到达最大时间停机),对web请求产生的线程暂时未找到等待方式,不过web用户请求一般都由运维在k8s和nginx层面进行路由处理。
另外需要注意终止方法调用的最大等待时间,要根据程序设计,提供一个合理的值,避免线程池中存在未执行完成的线程。
@Configuration
public class ShutdownHook {
public ShutdownHook() {
Runtime.getRuntime().addShutdownHook(new Thread(() -> {
ThreadPoolFactory.shutdown();
try {
ThreadPoolFactory.awaitTermination(30, TimeUnit.SECONDS);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
}));
}
}
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。