您可以实现多个HealthIndicators,它们都会对UP 或DOWN 的最终整体价值作出贡献。最终值是所有其他值的聚合(由StatusAggregator 确定)。
示例 1(健康)
@Component
public class ExampleOneHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// do something to check health
// inspect the return
// healthy
return Health.up().build();
}
}
示例 2(不健康)
@Component
public class ExampleTwoHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// do something to check health
// inspect the return
// unhealthy
return Health.down().build();
}
}
示例 3(不健康的细节)
@Component
public class ExampleThreeHealthIndicator implements HealthIndicator {
@Override
public Health health() {
// do something to check health
// inspect the return
// unhealthy with details
return Health.down()
.withDetail("reason", "details about why it failed")
.build();
}
}
通过上述三个示例,并将management.endpoint.health.show-details 设置为always(在application.properties 中),调用/actuator/health 时会得到以下结果。
{
"status": "DOWN",
"components": {
"diskSpace": {
"status": "UP",
"details": {
"total": 1000240963584,
"free": 880857858048,
"threshold": 10485760
}
},
"exampleOne": {
"status": "UP"
},
"exampleThree": {
"status": "DOWN",
"details": {
"reason": "details about why it failed"
}
},
"exampleTwo": {
"status": "DOWN"
},
"ping": {
"status": "UP"
}
}
}
响应中的名称是HealthIndicator 之前的类名(驼峰式)(例如ExampleOneHealthIndicator --> exampleOne)
其他名称(例如diskSpace 或ping)来自内置的健康检查,并且类名的命名与您期望的一样(DiskSpaceHealthIndicator 和PingHealthIndicator)
请注意,顶级status 是DOWN。这是由StatusAggregator 确定的。默认是https://docs.spring.io/spring-boot/docs/current/api/org/springframework/boot/actuate/health/SimpleStatusAggregator.html
示例代码
https://github.com/dustinschultz/spring-boot-actuator-custom-health-checks