简体   繁体   中英

SpringBoot Response Time using RestTemplate

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!

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

Yes, make a start and a finish timestamp and measure the difference, eg

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM