Spring boot actuator MySQL database health check
I would check the documentation - Exposing the full details anonymously requires to disable the security of the actuator.
If that's not what you want, you can take full control of the security and write your own rules using Spring Security.
I have used my own way of checking a database connection. Below solutions are very simple you can modify as according to your need. I know this is not specific to actuators, though it is the kinda same approach to solve when you don't wanna use the actuators.
@RestController
@RequestMapping("/api/db/")
public class DbHealthCheckController {
@Autowired
JdbcTemplate template;
private final Logger LOGGER = LoggerFactory.getLogger(this.getClass());
@GetMapping("/health")
public ResponseEntity<?> dbHealthCheck() {
LOGGER.info("checking db health");
try {
int errorCode = check(); // perform some specific health check
if (errorCode != 1)
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(false, "down"));
return ResponseEntity.ok(new ApiResponse(true, "Up"));
} catch (Exception ex) {
ex.printStackTrace();
LOGGER.error("Error Occured" + ex.getMessage());
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(new ApiResponse(false, "Down"));
}
}
public int check() {
List<Object> results = template.query("select 1 from dual", new
SingleColumnRowMapper<>());
return results.size();
}
}
ApiResponse
is a simple POJO class with 2 attributes Boolean success
and String message
.
Add this configuration to your application.properties file
management.endpoint.health.show-details=always