|
| 1 | +// Source: https://www.naiyerasif.com/post/2021/03/01/java-based-health-check-for-docker/ |
| 2 | +// Original code license: CC BY-SA 4.0 | https://www.naiyerasif.com/about/#frequently-asked-questions |
| 3 | + |
| 4 | +/** |
| 5 | + * How to compile: |
| 6 | + * javac HealthCheck.java |
| 7 | + * jar --create --file HealthCheck.jar --main-class HealthCheck HealthCheck.class |
| 8 | + * rm HealthCheck.class |
| 9 | + * |
| 10 | + * Remember to compile and/or target for the proper Java version. |
| 11 | + * Currently Tiamat requires 21, while others could support 25. |
| 12 | + * So 21 is used as the baseline support level. |
| 13 | + */ |
| 14 | + |
| 15 | +import java.io.IOException; |
| 16 | +import java.net.URI; |
| 17 | +import java.net.http.HttpClient; |
| 18 | +import java.net.http.HttpRequest; |
| 19 | +import java.net.http.HttpResponse.BodyHandlers; |
| 20 | + |
| 21 | +public class HealthCheck { |
| 22 | + public static void main(String[] args) throws IOException, InterruptedException { |
| 23 | + final var client = HttpClient.newHttpClient(); |
| 24 | + final var request = HttpRequest.newBuilder() |
| 25 | + .uri(URI.create("http://localhost:8080/actuator/health")) |
| 26 | + .header("accept", "application/json") |
| 27 | + .build(); |
| 28 | + |
| 29 | + final var response = client.send(request, BodyHandlers.ofString()); |
| 30 | + final var body = response.body(); |
| 31 | + |
| 32 | + System.out.print("Status: " + response.statusCode()); |
| 33 | + System.out.print(" | body: " + body); |
| 34 | + System.out.println(); |
| 35 | + |
| 36 | + if (response.statusCode() != 200 || !body.contains("UP")) { |
| 37 | + System.err.println("Service is not UP!"); |
| 38 | + System.exit(1); |
| 39 | + } else { |
| 40 | + System.exit(0); |
| 41 | + } |
| 42 | + } |
| 43 | +} |
0 commit comments