DEV Community

Arpit
Arpit

Posted on

Dynamic health-checks with spring boot

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"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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.

But, there is another way to register a health indicator, while the system is running, this is using HealthContributorRegistry. 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);
    }
}
Enter fullscreen mode Exit fullscreen mode

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());
Enter fullscreen mode Exit fullscreen mode

Your MyNewServiceImpl.java should implement HealthIndicator.

{
  "status": "UP",
  "components": {
    "ping": {
      "status": "UP"
    },
        "myNewService": {
      "status": "UP"
    }
  }
}
Enter fullscreen mode Exit fullscreen mode

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

healthContributorRegistry.unregisterContributor("myNewService");
Enter fullscreen mode Exit fullscreen mode

Hope this helps you, your application and your application's consumers stay healthy 🙂

Spring Boot documentation
Originally published here

Top comments (1)

Collapse
 
simondoll23 profile image
simondoll23

Hi, thanks for sharing such an informative content, I am sharing this with my Acupuncture clinic Peterborough.

Some comments may only be visible to logged-in visitors. Sign in to view all comments.