I’ve setup a healthcheck actuator with the endpoint /actuator/health, which produces something like the following for my application when you go to the URL:
{"status":"UP","app":{"status":"UP"},"db":{"status":"UP"}}
Is there a way I can access these results in my Java code using the Spring APIs? I’m monitoring for any that go down and sending out slack notifications when they do, I’m particularly interested in monitoring when the DB goes down. I’ve already got the method that creates the slack notification, I just need the name of the component that has gone down (i.e. db).
Can anyone help with this?
Hopefully my question makes sense, I’m pretty new to this still.
Edit: I’ve @Override Health, if the whole app goes down it goes into this, not sure if there is a way at this stage to get what else is down at the time (db etc) and pass into the slack method?:
@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(); } }
Advertisement
Answer
To get more details of the health status you can add following in your application.properties
management.endpoint.health.enabled=true management.endpoint.health.show-details=always
After that, you will get more information as below.
{ "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"); }