Spring Boot Actuator Database Health Check

By | 2018-11-16T01:24:30+00:00 November 14th, 2018|Spring Boot|0 Comments

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 🙂

About the Author:

Hi Folks, you have reach this so far, that shows you like what you are learning. Then why don't you support us to improve for bettor tutorials by leaving your valuable comments and why not you keep in touch with us for latest updates on your favorite blog @ facebook , twitter , Or Google+ ,

Leave A Comment