[英]SpringBoot Response Time using RestTemplate
Is there anyway to measure response time of a restTemplate in SpringBoot.无论如何测量SpringBoot中restTemplate的响应时间。
I'm calling an API this way, a Sync rest.我以这种方式调用 API,同步休息。 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.我可以使用另一个框架来做其余的调用,不需要是restTemplate,我只想使用SpringBoot调用一个外部API,看看需要多长时间才能响应。
Thank you!谢谢!
Is there anyway to measure response time of a restTemplate in SpringBoot.
无论如何测量SpringBoot中restTemplate的响应时间。
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如果您像下面这样注册一个
RestTemplate
@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:您将使用 Spring Boot 执行器免费获得传出请求指标
http.client.requests
,例如使用 Prometheus 作为监控系统:
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
:使用
HttpClient
和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.给出
GET https://stackoverflow.com/ took 395 ms
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.