15.3.2 自定义健康指标

对于一些常见的外部系统,与 Spring 应用程序集成时,Spring Boot 附带了几个现成的健康状况指示器,可提供它们的健康状况。但有时,您可能发现有一些外部系统,Spring Boot 并没有为其提供健康状况指示器。

例如,您的应用程序可能与遗留大型机应用程序集成,应用程序的健康状况,可能会受到遗留系统健康状况的影响。要创建自定义健康状况指示器,需创建一个实现 HealthIndicator 接口的类。

实际上,Taco Cloud 服务并不需要自定义健康指标,因为 Spring Boot 所提供的已经足够了。但为了展示如何开发自定义健康指示器,考虑以下程序清单,它展示了 HealthIndicator 的简单实现。其中选择一天中某个时间,随机地展示其健康状况。

程序清单 15.5 HealthIndicator 的非正常实现。

package tacos.tacos;
import java.util.Calendar;
import org.springframework.boot.actuate.health.Health;
import org.springframework.boot.actuate.health.HealthIndicator;
import org.springframework.stereotype.Component;
@Component
public class WackoHealthIndicator implements HealthIndicator {
@Override
  public Health health() {
    int hour = Calendar.getInstance().get(Calendar.HOUR_OF_DAY);
    if (hour > 12) {
        return Health
            .outOfService()
            .withDetail("reason",
                "I'm out of service after lunchtime")
            .withDetail("hour", hour)
            .build();
    }
    if (Math.random() < 0.1) {
        return Health
            .down()
            .withDetail("reason", "I break 10% of the time")
            .build();
    }
    return Health
        .up()
        .withDetail("reason", "All is good!")
        .build();
  }
}

这个疯狂的健康指示器首先检查当前时间,如果是中午之后,返回 OUT_OF_SERVICE 的健康状况,并提供一些详细信息来解释故障原因。

即使是在午餐前,健康指标也有 10% 的可能性会报告 DOWN 的状态,因为它使用一个随机数来决定它是否正常运行。如果随机数字小于 0.1,状态将报告为 DOWN 。否则,状态为 UP。

显然,清单 15.5 中的健康状况指示器,在真实环境中任何情况下都不会有用。但是想象一下,如果代码中不是用随机数,而是远程调用某个外部系统并确定其状态。在这种情况下,这将是一个非常有用的健康状况指示器。

results matching ""

    No results matching ""