Spring boot执行器MySQL数据库健康检查

问题描述 投票:0回答:6

我设计了一个演示 Spring Boot 应用程序与 MySQL 数据库的 CRUD 操作。我的application.properties文件如下。

spring.boot.admin.url=http://localhost:8081
spring.datasource.url= jdbc:mysql://localhost:3306/springbootdb
spring.datasource.username=root
spring.datasource.password=admin
endpoints.health.sensitive=false
management.health.db.enabled=true
management.health.defaults.enabled=true
management.health.diskspace.enabled=true
spring.jpa.hibernate.ddl-auto=create-drop

弹簧致动器的POM.xml如下。

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
<dependency>
    <groupId>de.codecentric</groupId>
    <artifactId>spring-boot-admin-starter-client</artifactId>
    <version>1.3.4</version>
</dependency>

当我尝试点击网址“http://localhost:8080/health”时,我收到 {"status":"UP"} 作为响应。我想用 Spring Boot Actuator 监控我的数据库(MySQL)。我想查看我的数据库状态。

有人可以帮忙吗?

java mysql spring spring-boot spring-boot-actuator
6个回答
7
投票

我会检查文档 - 匿名公开完整详细信息需要禁用执行器的安全性。

如果这不是您想要的,您可以完全控制安全性并使用 Spring Security 编写自己的规则。


5
投票

将此配置添加到您的 application.properties 文件

management.endpoint.health.show-details=always 

3
投票

在 Spring 2.2.x 版本中是:

management.endpoint.health.show-details=always

默认情况下,这个道具永远没有价值。


3
投票

我使用了自己的方法来检查数据库连接。以下解决方案非常简单,您可以根据需要进行修改。我知道这并不是执行器特有的,尽管当您不想使用执行器时,这与解决问题的方法有点相同。

@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"));
    }
}

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

ApiResponse
是一个简单的 POJO 类,具有 2 个属性
Boolean success and String message


1
投票

如果您使用 Spring Security,则默认情况下会为执行器启用安全性。

将其添加到您的属性文件中 -

management.security.enabled= false

在属性文件中添加用户名和密码 -

security.user.name= username
security.user.password = password

并使用这些凭据访问执行器端点。


0
投票

调用 http://localhost:8080/actuator 端点时,必须有如下端点。

"health-component": {
  "href": "http://localhost:8080/actuator/health/{component}",
  "templated": true
}

就我而言,我在应用程序中使用 mongodb。我调用 http://localhost:8080/actuator/health/mongo 端点它返回 mongodb health。

{
  "status": "UP",
  "details": {
     "version": "2.6.0"
  }
}
© www.soinside.com 2019 - 2024. All rights reserved.