【问题标题】:Spring Boot Actuator - Custom Health EndpointSpring Boot Actuator - 自定义健康端点
【发布时间】:2023-03-10 12:51:01
【问题描述】:

我正在使用 SpringBoot Actuator 来返回应用程序的运行状况。

public class HealthMonitor implements HealthIndicator {

    @Override
    public Health health() {
        int errorCode = check();
        if (errorCode != 0) {
            return Health.down().withDetail("Error Code", errorCode).build();
        }
        return Health.up().build();
    }

    public int check() {
        return 0;
    }

}

我看到下面的回复

{
  "status": "UP",
  "diskSpace": {
    "status": "UP",
    "free": 55020113920,
    "threshold": 10485760
  },
  "db": {
    "status": "UP",
    "database": "Oracle",
    "hello": "Hello"
  }
}

我想返回类似于下面的响应

{status: "Healthy"}

有办法吗?

【问题讨论】:

  • 检查errorCode后返回您的自定义响应,而不是返回Health实例
  • 在这种情况下我不应该实施 HealthIndicator 吗?有没有办法像我提到的那样使用 Health 实例返回自定义消息?
  • 我认为Health 是一些普通的课程。我自己尝试过,我现在唯一能想到的方法是保护这个服务不被外部使用,并创建一个类似/customHealth的自定义服务,并在服务器上使用这个/health服务来获取自定义服务中的状态信息。
  • 谢谢@11thdimension。请发布它作为答案,我会接受它
  • 这只是一个建议。如果我确实实现了这一点,那么我会将其发布为答案,感谢您的考虑。如果您实施它,然后将其发布为有助于他人的答案。

标签: java spring spring-boot spring-boot-actuator


【解决方案1】:

要自定义您的状态消息,有一种方法名为:withDetail()。所以当你写 return Health.up().build(); 时,只需将其替换为

return Health.up().withDetail("My Application Status","Healthy")

所以这会给

{My Application Status: "Healthy"}

【讨论】:

    【解决方案2】:

    我认为您无法说服提供的 Spring Boot 运行状况端点以截然不同的格式显示。

    大部分的Spring源码都很清晰,这个也不例外。查看org.springframework.boot.actuate.endpoint.HealthEndpoint 的源代码,您会看到它有一个invoke() 方法,该方法返回一个Health。您看到的 JSON 是 Jackson 对该对象的编组。

    但是,您可以创建自己的端点,以与 HealthEndpoint 完全相同的方式扩展 AbstractEndpoint,返回您喜欢的任何类。

    您甚至可以将其委托给 HealthEndpoint bean:

     public MyHealthEndpoint(HealthEndpoint delegate) {
         this.delegate = delegate;
     }
    
     @Override
     public MyHealth invoke() {
          Health health = delegate.invoke();
          return new MyHealth(health.getStatus());
     }
    

    【讨论】:

      【解决方案3】:

      Spring Boot 及其健康指标具有很大的灵活性。

      首先,根据您服务的复杂程度,您可能不需要上面描述的 HealthIndicator。开箱即用,Spring Boot 将根据您的弹簧配置返回“状态”。这包括数据库(SQL 和一些 noSQL)、邮件、JMS 和其他。这在section 47.6.1的最新 Spring Boot 文档中有所描述

      返回你想要的最简单的方法,不管有没有 HealthIndicator 类,是在你的 application.properties 中设置一个属性:

      endpoints.health.sensitive=true

      这可能仅适用于 Spring Boot 的更高版本(1.4 之后?)。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-24
        • 2015-12-06
        • 2023-03-26
        • 1970-01-01
        • 2019-03-10
        • 1970-01-01
        相关资源
        最近更新 更多