Spring Boot Actuator 健康检查

Spring Boot Actuator 提供了开箱即用的健康检查功能。

添加依赖

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

配置

application.yml
management:
  endpoints:
    web:
      exposure:
        include: health,info,metrics
      base-path: /actuator
  endpoint:
    health:
      show-details: always
      probes:
        enabled: true
  health:
    livenessState:
      enabled: true
    readinessState:
      enabled: true

自定义健康检查

CustomHealthIndicator.java
@Component
public class DatabaseHealthIndicator implements HealthIndicator {

    @Autowired
    private DataSource dataSource;

    @Override
    public Health health() {
        try {
            // 执行健康检查
            jdbcTemplate.execute("SELECT 1");

            return Health.up()
                .withDetail("database", "MySQL")
                .withDetail("status", "Connected")
                .build();
        } catch (Exception e) {
            return Health.down()
                .withDetail("error", e.getMessage())
                .build();
        }
    }
}

本章总结

核心要点

  1. Spring Boot Actuator 提供开箱即用的健康检查
  2. 可以自定义健康检查器检查特定依赖
  3. K8s 探针可以集成 Actuator