1

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?

Fábio
  • 3,291
  • 5
  • 36
  • 49
  • Did you find a good solution? I thought maybe setting the readiness state to refusing traffic after the application starts up, but not sure how stable that will be. – reactive-core Jun 26 '23 at 21:16
  • @reactive-core I used the solution posted by Poklakni, Spring will wait until all event listeners finish before setting the LivenessState and ReadinessState – Fábio Jul 04 '23 at 22:25

1 Answers1

1

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

Poklakni
  • 193
  • 2
  • 10