spring_reference/V. Spring Boot Actuator/40.3.2. Writing custom Heal...

29 lines
1.9 KiB
Markdown
Raw Normal View History

### 40.3.2. 编写自定义HealthIndicators
想提供自定义健康信息,你可以注册实现了[HealthIndicator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans。你需要提供一个health()方法的实现并返回一个Health响应。Health响应需要包含一个status和可选的用于展示的详情。
```java
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class MyHealth implements HealthIndicator {
@Override
public Health health() {
int errorCode = check(); // perform some specific health check
if (errorCode != 0) {
return Health.down().withDetail("Error Code", errorCode).build();
}
return Health.up().build();
}
}
```
除了Spring Boot预定义的[Status](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java)类型Health也可以返回一个代表新的系统状态的自定义Status。在这种情况下需要提供一个[HealthAggregator](http://github.com/spring-projects/spring-boot/tree/master/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthAggregator.java)接口的自定义实现或使用management.health.status.order属性配置默认的实现。
例如假设一个新的代码为FATAL的Status被用于你的一个HealthIndicator实现中。为了配置严重程度你需要将下面的配置添加到application属性文件中
```java
management.health.status.order: DOWN, OUT_OF_SERVICE, UNKNOWN, UP
```
如果使用HTTP访问health端点你可能想要注册自定义的status并使用HealthMvcEndpoint进行映射。例如你可以将FATAL映射为HttpStatus.SERVICE_UNAVAILABLE。