Home > front end >  SpringBoot Response Time using RestTemplate
SpringBoot Response Time using RestTemplate

Time:07-26

Is there anyway to measure response time of a restTemplate in SpringBoot.

I'm calling an API this way, a Sync rest. Is there anyway to measure a Async call too? Or just Sync calls?

    public void execute(Request request) {
    this.restTemplate.postForObject(System.getenv("URL"), request, String.class);
}

I can use another framework to do the rest call, don't need to be restTemplate, I just want to call an external API using SpringBoot and see how long does take to respond.

Thank you!

CodePudding user response:

Is there anyway to measure response time of a restTemplate in SpringBoot.

Yes, make a start and a finish timestamp and measure the difference, e.g

var start = Instant.now();
this.restTemplate.postForObject(System.getenv("URL"), request, String.class);
long duration = Duration.between(start, Instant.now()).toMillis();

However, if you want to keep track of the response time for outgoing requests, I would choose metrics as my first place to look at.

If you register a RestTemplate like below

  @Bean
  public RestTemplate restTemplate(RestTemplateBuilder restTemplateBuilder) {
    return restTemplateBuilder.build();
  }

you will get the outgoing request metric http.client.requests for free utilizing the Spring Boot actuator, example using Prometheus as monitoring system:

http_client_requests_seconds_max{clientName="stackoverflow.com",method="GET",outcome="SUCCESS",status="200",uri="/",} 0.398269736

Is there anyway to measure a Async call too?

Yes, make a start and a finish timestamp and measure the difference inside the callback from the async invocation. Example using HttpClient and CompletableFuture:

    var start = Instant.now();
    var completableFuture = HttpClient.newBuilder()
        .build()
        .sendAsync(request, HttpResponse.BodyHandlers.ofString())
        .thenAccept(response -> {
          long duration = Duration.between(start, Instant.now()).toMillis();
          log.info("{} {} took {} ms", request.method(), request.uri(), duration);
        });
    completableFuture.join();

Gives GET https://stackoverflow.com/ took 395 ms in the log.

  • Related