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

如何解决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);
    }
}

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-