# 50.9.2 编写自定义HealthIndicator

你可以注册实现[HealthIndicator](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthIndicator.java)接口的Spring beans来提供自定义健康信息。你需要实现`health()`方法，并返回一个`Health`响应，该响应需要包含一个`status`和其他用于展示的详情。下面的代码展示了一个`HealthIndicator`实现类的例子：

```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();
    }

}
```

**注** 对于给定`HealthIndicator`的标识是bean name去掉`HealthIndicator`后缀剩下的部分。在以上示例中，可以在`my`的实体中获取健康信息。

除Spring Boot预定义的[`Status`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/Status.java)类型，`Health`也可以返回一个代表新的系统状态的自定义`Status`。在这种情况下，你需要提供一个[`HealthAggregator`](https://github.com/spring-projects/spring-boot/tree/v2.0.0.RELEASE/spring-boot-project/spring-boot-actuator/src/main/java/org/springframework/boot/actuate/health/HealthAggregator.java)接口的自定义实现，或使用`management.health.status.order`属性配置默认实现。

例如，假设一个新的，代码为`FATAL`的`Status`被用于你的一个`HealthIndicator`实现中。为了配置严重性级别，你需要将以下配置添加到application属性文件中：

```
management.health.status.order=FATAL, DOWN, OUT_OF_SERVICE, UNKNOWN, UP
```

在回应中的HTTP状态码反映了全体的健康状况（例如，`UP`映射到200，`OUT_OF_SERVICE`和`DOWN`映射到503）。如果使用HTTP访问health端点，你可能想要注册自定义的status。例如，你可以将`FATAL`映射为503（服务不可用）。

```
management.health.status.http-mapping.FATAL=503
```

**注** 如果你需要更多的控制，你可以定义你自己的`HealthStatusHttpMapper`bean。

下面的表格展示了内建状态的默认状态映射：

| 状态               | 映射                         |
| ---------------- | -------------------------- |
| DOWN             | SERVICE\_UNAVAILABLE (503) |
| OUT\_OF\_SERVICE | SERVICE\_UNAVAILABLE (503) |
| UP               | 默认无映射，所以http状态是200         |
| UNKNOWN          | 默认无映射，所以http状态是200         |
