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

时间:2019-07-09 12:51:16

标签: java spring spring-boot cloudfoundry

我已经使用端点/ actuator / health设置了运行状况检查执行器,当您转到URL时,它将为我的应用程序生成类似以下内容的内容:

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

有没有一种方法可以使用Spring API在Java代码中访问这些结果?我正在监视所有发生故障的事件,并在发生故障时发出松弛通知,我特别想监视数据库何时发生故障。我已经有了创建延迟通知的方法,我只需要出现故障的组件的名称(即db)。

任何人都可以帮忙吗?

希望我的问题是有道理的,我对此还是很陌生。

编辑:我有@Override Health,如果整个应用程序都关闭了,它就会进入这个状态,不确定在此阶段是否有办法使当时发生的其他问题(db等)传递给松弛方法?:

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

1 个答案:

答案 0 :(得分:0)

要获取有关健康状况的更多详细信息,可以在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");
    }

enter image description here