Spring Boot and Java Melody Stopwatch
Sometimes we need to measure how long does a java process or a specific method take. We can use some traditional method like below to do that but it wont be too elegant
private void someMethod() {
Long timestamp = System.currentTimeMillis();
// do some process
logger.info(System.currentTimeMillis()-timestamp)
}
It looks good but we are unable to generate a report or statistics for this. And this is where Java Melody’s Stopwatch comes into the picture. It can measure the time needed for a specific process and generate report and statistics for it.
This is how it works,
public class RestService {
public void callRestAPIOne() {
try (Stopwatch stopwatch = new Stopwatch("stopwatch-for-one-todo")) {
try {
HttpRequest request = HttpRequest.newBuilder().uri(new URI("https://jsonplaceholder.typicode.com/todos/1"))
.GET().build();
System.out.println(HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void callRestAPITwo() {
try (Stopwatch stopwatch = new Stopwatch("stopwatch-for-users")) {
try {
HttpRequest request = HttpRequest.newBuilder().uri(new URI("https://jsonplaceholder.typicode.com/users"))
.GET().build();
System.out.println(HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
public void callRestAPIThree() {
try (Stopwatch stopwatch = new Stopwatch("stopwatch-for-posts")) {
try {
HttpRequest request = HttpRequest.newBuilder().uri(new URI("https://jsonplaceholder.typicode.com/posts"))
.GET().build();
System.out.println(HttpClient.newHttpClient().send(request, HttpResponse.BodyHandlers.ofString()).body());
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
