Here I am going to show how to check database health using Spring boot actuator health endpoint.

Spring Boot Actuator Database Health Check:

Include the spring boot actuator dependency in pom.xml

pom.xml
<dependency>
  <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>

We can do this check in two different solutions.

Solution-1:

Enabling the management config property in application.properties/yml file.

application.properties
management.endpoints.health.sensitive=false
management.health.db.enabled=true
management.health.defaults.enabled=true
management.endpoint.health.show-details=always

 

Run the Application and access actuator health endpoint.

http://localhost:8080/actuator/health

Spring Boot Actuator Database Health Check-min

Solution-2:

Creating the custom Actuator service.

  • Creating DbHealthCheck class implementing HealthIndicator and override health() method.
  • Using JdbcTemplate, execute the sample SQL query to check whether the database connected or not.
DbHealthCheck.java
package com.onlinetutorialspoint.actuator;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.jdbc.core.SingleColumnRowMapper;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
public class DbHealthCheck implements HealthIndicator {
    @Autowired
    JdbcTemplate template;
    @Override
    public Health health() {
        int errorCode = check(); // perform some specific health check
        if (errorCode != 1) {
            return Health.down().withDetail("Error Code", 500).build();
        }
        return Health.up().build();
    }

    public int check(){
        List<Object> results = template.query("select 1 from dual",
                new SingleColumnRowMapper<>());
        return results.size();
    }
}

Run the application.

http://localhost:8080/actuator/health

Spring Boot Actuator Database Health Check 2-min

References:

Spring Boot Production ready endpoints

Spring Boot Actuator

Happy Learning 🙂