我已经使用端点/ actuator / health设置了运行状况检查执行器,当您转到URL时,它将为我的应用程序生成类似以下内容的内容:
{"status":"UP","app":{"status":"UP"},"db":{"status":"UP"}}
有什么方法可以使用Spring API在Java代码中访问这些结果?我正在监视所有发生故障的事件,并在发生故障时发出松弛通知,我特别想监视数据库何时发生故障。我已经有了创建延迟通知的方法,我只需要出现故障的组件的名称(即db)。
有人能帮忙吗?
希望我的问题是有道理的,但我对此仍然很陌生。
编辑:我有@Override Health,如果整个应用程序都关闭了,它就会进入这个状态,不确定在此阶段是否有办法使当时发生的其他故障(db等)传递给slack方法? :
@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");
}