本文目录导读:

我来详细介绍 SpringBoot 健康检查端点和监控相关内容。
基础健康检查端点
1 启用 Actuator
<!-- pom.xml -->
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-actuator</artifactId>
</dependency>
2 配置文件
# application.yml
management:
endpoints:
web:
exposure:
include: health,info,metrics,env,beans,loggers
# 或使用 * 暴露所有端点
# include: "*"
endpoint:
health:
show-details: always # 显示详细信息
show-components: always # 显示组件状态
健康检查端点配置
1 核心配置选项
management:
health:
# 健康检查缓存时间
cache:
timeout: 10000
# 默认健康指标
defaults:
enabled: true
# 磁盘空间检查
diskspace:
enabled: true
path: /tmp
threshold: 10GB
# 数据库健康检查
db:
enabled: true
# Redis健康检查
redis:
enabled: true
endpoint:
health:
# 自定义响应状态
status:
http-mapping:
UP: 200
DOWN: 503
OUT_OF_SERVICE: 503
自定义健康指标
1 实现 HealthIndicator
@Component
public class CustomHealthIndicator implements HealthIndicator {
@Override
public Health health() {
try {
// 执行健康检查逻辑
boolean isHealthy = checkServiceHealth();
if (isHealthy) {
return Health.up()
.withDetail("service", "running")
.withDetail("timestamp", System.currentTimeMillis())
.build();
} else {
return Health.down()
.withDetail("service", "unavailable")
.withDetail("error", "Service is not responding")
.build();
}
} catch (Exception e) {
return Health.down()
.withDetail("error", e.getMessage())
.build();
}
}
private boolean checkServiceHealth() {
// 实际的健康检查逻辑
return true;
}
}
2 使用 AbstractHealthIndicator
@Component
public class DatabaseHealthIndicator extends AbstractHealthIndicator {
@Autowired
private DataSource dataSource;
@Override
protected void doHealthCheck(Health.Builder builder) throws Exception {
try (Connection conn = dataSource.getConnection()) {
if (conn.isValid(5000)) {
builder.up()
.withDetail("database", "MySQL")
.withDetail("version", conn.getMetaData().getDatabaseProductVersion());
} else {
builder.down()
.withDetail("error", "Cannot connect to database");
}
}
}
}
常见健康检查指标
1 内置健康指标
management:
health:
# 启用所有内置健康指标
defaults:
enabled: true
# 各组件健康检查配置
diskspace:
enabled: true
db:
enabled: true
elasticsearch:
enabled: true
influxdb:
enabled: true
jms:
enabled: true
ldap:
enabled: true
mail:
enabled: true
mongo:
enabled: true
neo4j:
enabled: true
ping:
enabled: true
rabbit:
enabled: true
redis:
enabled: true
solr:
enabled: true
2 自定义健康检查分组
management:
endpoint:
health:
group:
custom-group:
include: db,redis,custom
show-details: always
status:
http-mapping:
UP: 200
DOWN: 503
健康检查API使用
1 访问健康检查端点
# 基本健康检查 GET /actuator/health # 详细健康检查 GET /actuator/health?format=detailed # 健康分组检查 GET /actuator/health/custom-group
2 响应示例
{
"status": "UP",
"components": {
"db": {
"status": "UP",
"details": {
"database": "MySQL",
"validationQuery": "isValid()"
}
},
"diskSpace": {
"status": "UP",
"details": {
"total": 499963170816,
"free": 123456789012,
"threshold": 10485760
}
},
"redis": {
"status": "UP",
"details": {
"version": "6.2.6"
}
},
"custom": {
"status": "UP",
"details": {
"service": "running",
"timestamp": 1634567890123
}
}
}
}
监控集成
1 Prometheus 集成
<dependency>
<groupId>io.micrometer</groupId>
<artifactId>micrometer-registry-prometheus</artifactId>
</dependency>
management:
endpoints:
web:
exposure:
include: prometheus,health
metrics:
export:
prometheus:
enabled: true
2 Grafana 集成
# application.yml
management:
endpoints:
web:
base-path: /actuator
metrics:
tags:
application: ${spring.application.name}
安全配置
1 保护健康检查端点
@Configuration
public class SecurityConfig extends WebSecurityConfigurerAdapter {
@Override
protected void configure(HttpSecurity http) throws Exception {
http
.authorizeRequests()
.antMatchers("/actuator/health").permitAll() // 允许匿名访问
.antMatchers("/actuator/**").hasRole("ADMIN") // 需要管理员权限
.anyRequest().authenticated()
.and()
.httpBasic();
}
}
2 自定义响应状态码
management:
endpoint:
health:
status:
http-mapping:
UP: 200
DOWN: 503
OUT_OF_SERVICE: 503
UNKNOWN: 200
高级配置示例
1 完整配置
spring:
application:
name: my-service
server:
port: 8080
management:
server:
port: 8081 # 监控端口与业务端口分离
address: 127.0.0.1 # 只监听本地
endpoints:
web:
base-path: /internal # 自定义路径
exposure:
include: health,info,metrics,prometheus
exclude: env,beans # 排除敏感端点
cors:
allowed-origins: http://example.com
allowed-methods: GET,POST
endpoint:
health:
show-details: when-authorized # 仅授权用户查看详情
roles: ADMIN
cache:
time-to-live: 10s # 缓存10秒
# 自定义健康检查
spring:
datasource:
hikari:
connection-test-query: SELECT 1
validation-timeout: 3000
2 自定义健康检查器注册
@Component
public class HealthCheckConfig {
@Bean
public ReactiveHealthIndicator reactiveHealthChecker() {
return () -> Mono.just(Health.up()
.withDetail("service", "reactive")
.build());
}
@Bean
public HealthAggregator healthAggregator() {
OrderedHealthAggregator aggregator = new OrderedHealthAggregator();
aggregator.setStatusOrder(Status.DOWN, Status.OUT_OF_SERVICE, Status.UP, Status.UNKNOWN);
return aggregator;
}
}
最佳实践
1 健康检查设计原则
@Component
public class BestPracticeHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// 1. 快速返回结果(设置超时)
// 2. 不依赖外部服务状态
// 3. 不执行耗时操作
// 4. 避免在健康检查中执行业务逻辑
return Health.up()
.withDetail("quick", "health check")
.build();
}
}
2 超时设置
management:
health:
defaults:
enabled: true
# 整体超时
status:
order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP
endpoint:
health:
time-to-live: 10000 # 缓存时间10秒
问题排查
1 常见问题
# 检查端点是否暴露 curl http://localhost:8080/actuator # 检查健康详情 curl http://localhost:8080/actuator/health # 查看所有端点 curl http://localhost:8080/actuator/beans
2 日志配置
logging:
level:
org.springframework.boot.actuate: DEBUG
org.springframework.boot.actuate.health: TRACE
通过以上配置,您可以构建一个完整、安全且可扩展的 SpringBoot 健康检查监控系统,记得根据实际需求调整配置,并注意在生产环境中保护敏感信息。