MicroProfile Health Check

Posted by Hayri Cicek on March 03, 2019


Health checks are used to determine if the service is running, shutdown, lack of disk space or maybe issues with the database connection. In this tutorial, we will use Eclipse MicroProfile Starter to generate a new project.

Eclipse MicroProfile Starter
Go to https://start.microprofile.io/ and follow the steps below to generate a new project.



Enter the Details as Follows
groupId: com.kodnito
artifactId: mp_health_example
MicroProfile Version: MP 2.1
MicroProfile Server: Open Liberty
Examples for specifications: Uncheck all examples except the Health Checks.

And that's it, just click Download button and your new project will be downloaded.
Unzip the zip file and open the project in your favorite IDE.
The Eclipse MicroProfile Starter generated an health check example inside com.kodnito.mp_health_example.health package.
Now open the ServiceHealthCheck file and see what the generator generated for us.
Beans annotated with @Health paired with @ApplicationScoped will be discovered automatically.
The ServiceHealthCheck implements the HealthCheck interface and overrides the call() method.

Open your terminal and go to the directory where the project lives and type the following command to start the application:


$ mvn clean package && java -jar target/mp_health_example.jar


Now visit http://localhost:8181/health and we have a simple health check already implemented for us.

MicroProfile Health Check

Open the ServiceHealthCheck file and change it to look like this:


@Health
@ApplicationScoped
public class ServiceHealthCheck implements HealthCheck {

    @Override
    public HealthCheckResponse call() {
        HealthCheckResponseBuilder responseBuilder = HealthCheckResponse.named(ServiceHealthCheck.class.getSimpleName());
        
        responseBuilder.withData("memory", Runtime.getRuntime().freeMemory());
        responseBuilder.withData("availableProcessors", Runtime.getRuntime().availableProcessors());
        
        return responseBuilder.state(true).build();

    }
}


Kill the application and restart it again:


$ mvn clean package && java -jar target/mp_health_example.jar


Now visit http://localhost:8181/health and we have new health checks.

MicroProfile Multiple Health Check It's really easy to add health checks to your application with MicroProfile Health and in this quick tutorial we learned how to quickly get started with MicroProfile Health and we added simple checks for free memory and available processors but you are not limited to those checks only, there is unlimited health checks you could add to your service.

You find this sample here GitHub


Share this: