配置文件

  1. management:
  2. server:
  3. port: 8889
  4. endpoints:
  5. web:
  6. exposure:
  7. #默认值访问health,info端点 用*可以包含全部端点
  8. include: "shutdown,health,info"
  9. endpoint:
  10. shutdown:
  11. enabled: true
  12. health:
  13. show-details: always

关闭 Tomcat

  1. @Slf4j
  2. public class CustomShutdown implements TomcatConnectorCustomizer,
  3. ApplicationListener<ContextClosedEvent> {
  4. private static final int TIME_OUT = 30;
  5. private volatile Connector connector;
  6. @Override
  7. public void customize(Connector connector) {
  8. this.connector = connector;
  9. }
  10. @Override
  11. public void onApplicationEvent(ContextClosedEvent event) {
  12. String displayName = "Web";
  13. if (event.getSource() instanceof AnnotationConfigApplicationContext ){
  14. displayName = ((AnnotationConfigApplicationContext) event.getSource()).getDisplayName();
  15. }/* Suspend all external requests*/
  16. this.connector.pause();
  17. /* Get ThreadPool For current connector */
  18. Executor executor = this.connector.getProtocolHandler().getExecutor();
  19. if (executor instanceof ThreadPoolExecutor) {
  20. log.warn("当前{}应用准备关闭",displayName);
  21. try {
  22. ThreadPoolExecutor threadPoolExecutor = (ThreadPoolExecutor) executor;
  23. /* Initializes a shutdown task after the current one has been processed task*/
  24. threadPoolExecutor.shutdown();
  25. if (!threadPoolExecutor.awaitTermination(TIME_OUT, TimeUnit.SECONDS)) {
  26. log.warn("当前{}应用等待超过最大时长{}秒,将强制关闭", displayName,TIME_OUT);
  27. /* Try shutDown Now*/
  28. threadPoolExecutor.shutdownNow();
  29. if (!threadPoolExecutor.awaitTermination(TIME_OUT, TimeUnit.SECONDS)) {
  30. log.error("强制关闭失败", TIME_OUT);
  31. }
  32. }
  33. } catch (InterruptedException e) {
  34. Thread.currentThread().interrupt();
  35. }
  36. }
  37. }
  38. }

添加 Connector 回调

  1. @Configuration
  2. public class ShutdownConfig {
  3. @Bean
  4. public CustomShutdown customShutdown() {
  5. return new CustomShutdown();
  6. }
  7. @Bean
  8. public ConfigurableServletWebServerFactory webServerFactory(final CustomShutdown customShutdown) {
  9. TomcatServletWebServerFactory tomcatServletWebServerFactory = new TomcatServletWebServerFactory();
  10. tomcatServletWebServerFactory.addConnectorCustomizers(customShutdown);
  11. return tomcatServletWebServerFactory;
  12. }
  13. }