Created - November 8, 2021

Health-check is an important part of any project that you create. You can deploy your service, and expose an endpoint that emits its health periodically. These endpoints could be called from your container, your dependent clients, your cloud deployment infrastructure, etc. As long as the service is healthy or "UP", the consumers are happy. When it goes down, the consumers can either pivot to something else, or show an error to the end user to wait till it's back up.

Dynamic Health-checks

Let's imagine you have a use-case, where your spring boot application is already up, and its talking to other systems, and you want to register a new health endpoint while your application is running. Spring boot will already give something like this already out of the box -

{
  "status": "UP",
  "components": {
    "ping": {
      "status": "UP"
    }
  }
}

So, the application is up and running now, and there is a new dependency that you have identified, that you want to register. Usually, the health-checks are static - either configured in the yaml / properties file or defined as part of your code by implementing [HealthIndicator](<https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/actuate/health/HealthIndicator.html>).

But, there is another way to register a health indicator, while the system is running, this is using [HealthContributorRegistry](<https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/actuate/health/HealthContributorRegistry.html>). Spring boot gives you this from the application context, so you can Autowire it in your bean.

@SpringBootApplication
public class Application {

	@Autowired
	HealthContributorRegistry healthContributorRegistry;
	
	public static void main(final String[] args) {
		SpringApplication.run(Application.class, args);
	}
}

Once you get the object, there are really simple methods to invoke to register or unregister contributors to your application while its running.

healthContributorRegistry.registerContributor("myNewService", new MyNewServiceImpl());

Your [MyNewServiceImpl.java](<http://MyNewServiceImpl.java>) should implement HealthIndicator.

{
  "status": "UP",
  "components": {
    "ping": {
      "status": "UP"
    },
		"myNewService": {
      "status": "UP"
    }
  }
}

You can also unregister it, if you want to remove something at runtime.

healthContributorRegistry.unregisterContributor("myNewService");
Powered by Fruition