我已经使用端点 /actuator/health 设置了一个运行状况检查执行器,当您访问 URL 时,它会为我的应用程序生成类似以下内容的内容:
{"status":"UP","app":{"status":"UP"},"db":{"status":"UP"}}
有没有办法可以使用 Spring API 在 Java 代码中访问这些结果?我正在监视任何发生故障的情况,并在发生故障时发送松弛通知,我对监视数据库何时发生故障特别感兴趣。我已经有了创建松弛通知的方法,我只需要已关闭的组件的名称(即 db)。
有人能帮忙吗?
希望我的问题有意义,我对此仍然很陌生。
编辑:我已经@Override Health,如果整个应用程序出现故障,就会进入此状态,不确定现阶段是否有办法获取当时出现的其他情况(数据库等)并传递给松弛方法? :
@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>"
}
}
}
}
Solution
@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");
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)