javaspringspring-boot

Start Spring Boot refusing traffic at first


Right after all the beans are created and started, Spring Boot sets the LivenessState to CORRECT and ReadinessState to ACCEPTING_TRAFFIC.

However, after my application starts, it still needs to load a bunch of data on a ContextRefreshedEvent event listener.

How do I prevent setting the ReadinessState to ACCEPTING_TRAFFIC automatically?


Solution

  • You can create your own HealthIndicator that marks your app as ready after the data is loaded

    @Component
    public class DataLoadingHealthIndicator implements HealthIndicator {
    
        private boolean dataLoaded = false;
    
        @EventListener
        public void handleContextRefresh(ContextRefreshedEvent event) {
            // Load your data here
            dataLoaded = true;
        }
    
        @Override
        public Health health() {
            if (dataLoaded) {
                return Health.up().build();
            } else {
                return Health.down().build();
            }
        }
    }
    

    if you don't want to load the data in the health indicator, you can fire a custom event right after you load the data and listen to that event in your custom health indicator.

    more useful info can be found here: java listen to ContextRefreshedEvent