如何在Java代码中访问Spring执行器运行状况检查的结果?

2022-08-15 00:00:00 spring java spring-boot cloud-foundry

我已经设置了一个带有端点/Actuator/Health的Health Check执行器,当您转到URL时,它会为我的应用程序生成类似以下内容:

{"status":"UP","app":{"status":"UP"},"db":{"status":"UP"}}

有没有办法可以使用SpringAPI在我的Java代码中访问这些结果?我正在监视任何发生故障的情况,并在发生故障时发送延迟通知,我对监视数据库何时发生故障特别感兴趣。我已经有了创建松弛通知的方法,我只需要发生故障的组件的名称(即db)。

有人能帮忙吗?

希望我的问题有道理,我还是个新手。

编辑:我已经@Override Health,如果整个应用程序都关闭了,它就会进入这个阶段,不确定在这个阶段是否有方法可以获得当时还关闭的内容(db等)并传递到Sack方法中?:

    @Override
    public Health health() {
        System.out.println("HealthIndicator called at " + LocalDateTime.now() + " state=" + (state?"Up":"Down"));
        if(state) {
            return Health.up().build();
        } else { 
    triggerSlackNotifications(failedComponent, status);
            return Health.down().build();
        }
    }

解决方案

要获取有关运行状况的更多详细信息,您可以在application.properties

中添加以下内容
management.endpoint.health.enabled=true
management.endpoint.health.show-details=always

之后,您将获得更多信息,如下所示。

{
    "status": "UP",
    "details": {
        "diskSpace": {
            "status": "UP",
            "details": {
                "total": 467848392704,
                "free": 69999702016,
                "threshold": 10485760
            }
        },
        "db": {
            "status": "UP",
            "details": {
                "database": "MySQL",
                "hello": 1
            }
        },
        "mail": {
            "status": "UP",
            "details": {
                "location": "smtp.gmail.com:<port>"
            }
        }
    }
}

解决方案

@GetMapping("/statusDB")
    public String healthCheck() throws IOException, JSONException
    {

          StringBuilder result = new StringBuilder();
          URL url = new URL("http://localhost:8080/actuator/health");
          HttpURLConnection conn = (HttpURLConnection) url.openConnection();
          conn.getResponseCode();
          BufferedReader rd = new BufferedReader(new InputStreamReader(conn.getInputStream()));
          String line;
          while ((line = rd.readLine()) != null) {
             result.append(line);
          }
          rd.close();
          System.out.println("Result: "+result.toString());

          JSONObject jsonObject =new JSONObject(result.toString());
          System.out.println("jsonObject: "+jsonObject);

          return "Status of Database is "+jsonObject.getJSONObject("details").getJSONObject("db").get("status");
    }

相关文章