如何让SpringBoot应用感知Tomcat Web服务器完全就绪?
如何监听Spring Boot中Tomcat服务器完全就绪的时机
方法1:监听ApplicationReadyEvent事件
Spring Boot提供的ApplicationReadyEvent会在应用所有Bean初始化完成、Web服务器完全启动并就绪后触发,此时调用/actuator/health接口可正常返回。
方式A:使用@EventListener注解
在任意Spring管理的Bean中添加监听方法:
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.event.EventListener; import org.springframework.stereotype.Component; @Component public class ServerReadyListener { @EventListener(ApplicationReadyEvent.class) public void onServerReady(ApplicationReadyEvent event) { // 执行服务器就绪后的业务逻辑 System.out.println("Tomcat服务器已完全就绪,可处理请求"); // 此时调用/actuator/health接口会成功 } }
方式B:实现ApplicationListener接口
import org.springframework.boot.context.event.ApplicationReadyEvent; import org.springframework.context.ApplicationListener; import org.springframework.stereotype.Component; @Component public class ServerReadyApplicationListener implements ApplicationListener<ApplicationReadyEvent> { @Override public void onApplicationEvent(ApplicationReadyEvent event) { System.out.println("Tomcat服务器已完全就绪"); // 执行就绪后的操作 } }
方法2:实现SmartLifecycle接口
SmartLifecycle可控制Bean的启动时机,通过设置足够大的phase值,确保start()方法在Web服务器启动完成后执行:
import org.springframework.context.SmartLifecycle; import org.springframework.stereotype.Component; @Component public class ServerReadyLifecycle implements SmartLifecycle { private boolean isRunning = false; @Override public void start() { System.out.println("Tomcat服务器已完全就绪"); // 执行就绪后的业务逻辑 isRunning = true; } @Override public void stop() { isRunning = false; } @Override public boolean isRunning() { return isRunning; } // 设置最大phase值,保证在Web服务器启动后执行 @Override public int getPhase() { return Integer.MAX_VALUE; } }
原方案失效原因
ServletContextListener的contextInitialized方法触发于ServletContext初始化阶段,此时Spring容器仍在初始化Bean,Web服务器的端点(如actuator的health)尚未完成注册,因此调用/actuator/health会失败。上述两种方法均在Spring Boot完整启动流程结束后触发,确保服务器完全就绪。
内容的提问来源于stack exchange,提问作者Philippe MESMEUR
相关产品推荐
相关产品推荐

