springboot中tomcat优雅退出

编程

1. 新增类

import lombok.extern.slf4j.Slf4j;

import org.apache.catalina.connector.Connector;

import org.apache.tomcat.util.threads.ThreadPoolExecutor;

import org.springframework.boot.web.embedded.tomcat.TomcatConnectorCustomizer;

import org.springframework.context.ApplicationListener;

import org.springframework.context.event.ContextClosedEvent;

import org.springframework.stereotype.Component;

import java.util.concurrent.Executor;

import java.util.concurrent.TimeUnit;

/**

*

* */

@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 contextClosedEvent) {

this.connector.pause();

Executor executor = this.connector.getProtocolHandler().getExecutor();

if (executor instanceof ThreadPoolExecutor) {

try {

ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;

threadPoolExecutor.shutdown();

if (!threadPoolExecutor.awaitTermination(waitTime, TimeUnit.SECONDS)) {

log.warn("Tomcat thread pool did not shut down gracefully within " + waitTime + " seconds. Proceeding with forceful shutdown");

}

} catch (InterruptedException ex) {

Thread.currentThread().interrupt();

}

}

}

}

2. 在main方法下加入

@Autowired

private GracefulShutdownTomcat gracefulShutdownTomcat;

@Bean

public ServletWebServerFactory servletContainer() {

TomcatServletWebServerFactory tomcat = new TomcatServletWebServerFactory();

tomcat.addConnectorCustomizers(gracefulShutdownTomcat);

return tomcat;

}

 

 

以上是 springboot中tomcat优雅退出 的全部内容, 来源链接: utcz.com/z/511855.html

回到顶部