sou*_*ica 14 tomcat spring-boot
在我的Spring Boot应用程序中,我需要等到(默认的Tomcat)Web服务器完全初始化并准备好接收流量,然后才将消息发送给其他应用程序,告诉他们向我发送HTTP请求(特别是一个监视系统,我的命中/health
).
我已经尝试将消息发送到其他应用程序,ApplicationListener<ContextRefreshedEvent>
但现在还为时尚早.其他应用程序尝试向我发出请求并失败.现在我已经延迟了,onApplicationEvent
并且它有效,但它是hacky和racy.
我也试过添加一个ServletContextInitializer
但是甚至更早被解雇了.
我假设我需要使用Tomcat API,但我想看看Boot API中是否有这样的东西.
And*_*son 19
最简单的方法是在SpringApplication.run()
返回后发送消息.在Tomcat(或任何其他受支持的嵌入式容器)完全启动并侦听配置的端口之前,此方法不会返回.然而,虽然这很简单,但它并不是一个非常简洁的方法,因为它混合了主配置类和一些应用程序的运行时逻辑的关注点.
相反,你可以使用SpringApplicationRunListener
.finished()
在Tomcat完全启动并侦听配置的端口之前,不会调用它.
创建一个名为src/main/resources/META-INF/spring.factories
列出运行侦听器的文件.例如:
org.springframework.boot.SpringApplicationRunListener=com.example.MyRunListener
Run Code Online (Sandbox Code Playgroud)
使用所需的构造函数和实现创建运行侦听器SpringApplicationRunListener
.例如:
package com.example;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.SpringApplicationRunListener;
import org.springframework.context.ConfigurableApplicationContext;
import org.springframework.core.env.ConfigurableEnvironment;
public class MyRunListener implements SpringApplicationRunListener {
public MyRunListener(SpringApplication application, String[] args) { }
@Override
public void starting() { }
@Override
public void environmentPrepared(ConfigurableEnvironment environment) { }
@Override
public void contextPrepared(ConfigurableApplicationContext context) { }
@Override
public void contextLoaded(ConfigurableApplicationContext context) { }
@Override
public void started(ConfigurableApplicationContext context) {
// Send message; Tomcat is running and listening on the configured port(s)
}
@Override
public void running(ConfigurableApplicationContext context) { }
@Override
public void failed(ConfigurableApplicationContext context, Throwable exception) { }
Run Code Online (Sandbox Code Playgroud)
从Spring Boot 1.3.0开始,这也可以通过实现来实现 ApplicationListener<ApplicationReadyEvent>
例:
public class MyApplicationListener implements ApplicationListener<ApplicationReadyEvent>, Ordered {
@Override
public void onApplicationEvent(ApplicationReadyEvent event) {
//do stuff now that application is ready
}
@Override
public int getOrder() {
return Ordered.LOWEST_PRECEDENCE;
}
}
Run Code Online (Sandbox Code Playgroud)
此外,如接受的答案中所述,您可以创建一个名为src/main/resources/META-INF/spring.factories
列出您的文件的文件ApplicationListener
.例如:
org.springframework.context.ApplicationListener=com.example.MyApplicationListener
Run Code Online (Sandbox Code Playgroud)
但是,在我的情况下,我只需要这个监听器在特定的配置文件下运行
所以我添加了以下属性 application-<profile_name>.properties
context.listener.classes=com.example.MyApplicationListener
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
7111 次 |
最近记录: |