Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 576
Fábio Avatar asked Mar 08 '26 18:03

Fábio


1 Answers

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

like image 136
Poklakni Avatar answered Mar 11 '26 06:03

Poklakni



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!