Spring Boot如何在启动期间彻底关闭

问题描述

我正在努力在我的Spring Boot 2.3.4应用程序中包括一个许可证密钥验证器,并且正在ContextRefreshedEvent上使用@EventListener以及SpringApplication.exit()来强制应用程序在启动时关闭(如果密钥无效。一切正常,看来该应用程序已关闭。但是,在应用程序上下文关闭之后,仍然有大量不必要的堆栈跟踪与任务计划程序仍在尝试启动。我的应用程序中有两个使用@Scheduled的bean,以供参考。

在这种情况下,有什么方法可以在启动期间更干净地强制关闭吗?我还尝试过监听ApplicationStartedEvent和ApplicationReadyEvent,但仍会喷出不同级别的堆栈跟踪。

明显的测试用例类,强制许可证无效:

@Component
public class LicenseValidator {
    private static final Logger LOGGER = LoggerFactory.getLogger(LicenseValidator.class);

    private final String licenseKey;

    public LicenseValidator(@Value("${app.license:}") String licenseKey) {
        this.licenseKey = licenseKey;
    }

    @EventListener
    public void onStartup(ContextRefreshedEvent event) {
        if (StringUtils.isEmpty(licenseKey)) {
            LOGGER.error("*** CRITICAL: LICENSE INVALID");
            SpringApplication.exit(event.getApplicationContext(),() -> 0);
        }
    }
}

关机期间的日志(已经处于调试模式):

2020-10-20 09:48:55.042  INFO 15272 --- [           main] o.s.b.w.embedded.tomcat.TomcatWebServer  : Tomcat started on port(s): 8080 (http) with context path ''
2020-10-20 09:48:55.042  INFO 15272 --- [           main] DeferredRepositoryInitializationListener : Triggering deferred initialization of Spring Data repositories…
2020-10-20 09:48:55.323  INFO 15272 --- [           main] DeferredRepositoryInitializationListener : Spring Data repositories initialized!
2020-10-20 09:48:55.323 ERROR 15272 --- [           main] c.n.myapp.LicenseValidator               : *** CRITICAL: LICENSE INVALID
2020-10-20 09:48:55.573  INFO 15272 --- [           main] j.LocalContainerEntityManagerfactorybean : Closing JPA EntityManagerFactory for persistence unit 'default'
2020-10-20 09:48:55.573  INFO 15272 --- [           main] o.s.s.c.ThreadPoolTaskScheduler          : Shutting down ExecutorService 'taskScheduler'
2020-10-20 09:48:55.573  INFO 15272 --- [           main] o.s.s.concurrent.ThreadPoolTaskExecutor  : Shutting down ExecutorService 'applicationTaskExecutor'
2020-10-20 09:48:55.573  INFO 15272 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown initiated...
2020-10-20 09:48:55.589  INFO 15272 --- [           main] com.zaxxer.hikari.HikariDataSource       : HikariPool-1 - Shutdown completed.
2020-10-20 09:48:55.605  INFO 15272 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-10-20 09:48:55.605  WARN 15272 --- [           main] ConfigServletWebServerApplicationContext : Exception encountered during context initialization - cancelling refresh attempt: org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties': Could not bind properties to 'TaskSchedulingProperties' : prefix=spring.task.scheduling,ignoreInvalidFields=false,ignoreUnkNownFields=true; nested exception is java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2d36e77e has been closed already
2020-10-20 09:48:55.605  INFO 15272 --- [           main] ConditionEvaluationReportLoggingListener : 

Error starting ApplicationContext. To display the conditions report re-run your application with 'debug' enabled.
2020-10-20 09:48:55.620 ERROR 15272 --- [           main] o.s.boot.SpringApplication               : Application run Failed

org.springframework.boot.context.properties.ConfigurationPropertiesBindException: Error creating bean with name 'spring.task.scheduling-org.springframework.boot.autoconfigure.task.TaskSchedulingProperties': Could not bind properties to 'TaskSchedulingProperties' : prefix=spring.task.scheduling,ignoreUnkNownFields=true; nested exception is java.lang.IllegalStateException: org.springframework.boot.web.servlet.context.AnnotationConfigServletWebServerApplicationContext@2d36e77e has been closed already
    at org.springframework.boot.context.properties.ConfigurationPropertiesBindingPostProcessor.bind(ConfigurationPropertiesBindingPostProcessor.java:92) ~[spring-boot-2.3.4.RELEASE.jar:2.3.4.RELEASE]
...

解决方法

作为一个想法和问题,可能会希望得到答案;) 您为什么还要启动其他的四季豆(如预定的东西等)? 根据您实际的应用程序,在应用程序启动期间可能会发生很多事情,其中​​一些实际上会更新您的环境状态:

举几个例子,让您了解启动过程中要做什么:

  • 如果您有Flyway,Flyway可能会在您的数据库上运行迁移
  • 如果Hibernate指示您这样做,它甚至可以为您创建模式
  • 也许您有ElasticSearch并在启动过程中创建了索引,谁知道

因此,据我所知, 检查许可证的代码应在所有这些内容之前运行,并且通常应尽可能早地运行

所以我可以考虑两种解决方案:

  1. 甚至在Spring Boot开始引导之前运行代码:
<TableCell align="center">
  <span data-tip={title}>
      <Highlighter highlightClassName="YourHighlightClass" searchWords={[searchValue]} autoEscape textToHighlight={title} />
      <ReactTooltip delayShow={500} effect="solid" border={false}/>
  </span>
</TableCell>
  1. 第一种方法可能具有一个缺点,即您不能依赖Spring的属性定义来指定许可证密钥。在这种情况下,您将需要在加载“环境”之后但在春季开始创建bean之前的某个时间运行许可证检查器。

Spring / spring引导确实具有这样的抽象,称为@SpringBootApplication public class Main { public static void main(...) { LicenceChecker.checkLicence(); SpringApplication.run(Main.class); } }

第1步:创建后处理器:

EnvironmentPostProcessor

第2步:注册后处理器:

  • 创建package foo.bar; import org.springframework.boot.env.EnvironmentPostProcessor; public class LicenceCheckingEnvironmentPostProcessor implements EnvironmentPostProcessor { public void postProcessEnvironment(ConfigurableEnvironment configurableEnvironment,SpringApplication springApplication) ... check the licence here ... // access the properties,profiles,whatever via the configurableEnvironment object } 文件并放在其中:
META-INF/spring.factories

应该可以

,

为了后代,我将继续充实它,添加更多的钩子,逻辑等。但是从Actuator的ShutdownEndpoint的基本思想出发,我已将LicenseValidator更改为@Scheduled,它可以触发单独的线程如果许可证无效,请正常关闭。在最终用法中,许可证密钥不是@Value属性,而是从数据库中读取的,并根据中央许可证服务器进行定期验证,等等。

@Component
public class LicenseValidator {
    private static final Logger LOGGER = LoggerFactory.getLogger(LicenseValidator.class);

    private final String licenseKey;

    private final ConfigurableApplicationContext ctx;

    public LicenseValidator(@Value("${app.license:}") String licenseKey,ConfigurableApplicationContext ctx) {
        this.licenseKey = licenseKey;
        this.ctx = ctx;
    }

    @Scheduled(fixedRate = 60000L)
    public void validateLicense() {
        if (StringUtils.isEmpty(licenseKey)) {
            LOGGER.error("*** CRITICAL: LICENSE INVALID");
            Thread shutdownThread = new Thread(this::shutdownApp);
            shutdownThread.setContextClassLoader(this.getClass().getClassLoader());
            shutdownThread.start();
        }
    }

    private void shutdownApp() {
        try {
            Thread.sleep(500);
        } catch (InterruptedException ignored) {}

        // could also be ctx.close(),but whatever floats your boat...
        SpringApplication.exit(ctx,() -> 0);
    }
}

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...