简体   繁体   English

如何使用 Java 11 标准 HTTPClient 测量 ASYNC 发送 HTTPRequest 的经过时间?

[英]How to measure the elapsed time of ASYNC sent HTTPRequest with Java 11 standard HTTPClient?

In one method, I create and send some HTTPRequests async, and add the CF to a list:在一种方法中,我创建并异步发送一些 HTTPRequest,并将 CF 添加到列表中:

// HTTPClient is Java11 standard, package java.net.http;
CompletableFuture<HttpResponse<String>> httpResponseCF = this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString());
list.add(httpResponseCF);

Later, in another method, I periodically check every 1second if some of my async sent HTTPRequests have already received:后来,在另一种方法中,如果我的一些异步发送的 HTTPRequest 已经收到,我会每隔 1 秒定期检查一次:

for(CompletableFuture<HttpResponse<String>> httpResponseCF : list){
  if (httpResponseCF.isDone()) {
    //print out: The time between sending HTTPRequest and receiving HTTPResponse is 25ms
  }
}

The question is, how to measure the exact elapsed request-time?问题是,如何测量准确的请求时间?

Something like the following should do the trick:像下面这样的东西应该可以解决问题:

long start = System.nanoTime();
CompletableFuture<HttpResponse<String>> httpResponseCF = 
    this.httpClient.sendAsync(httpRequest, BodyHandlers.ofString()).
    whenComplete((r,t) -> System.out.println("elapsed ns: "
                           + (System.nanoTime() - start)));

Disclaimer: I haven't actually compiled the above... It's also not the exact time but the best approximation you can get.免责声明:我实际上并没有编译上述内容......这也不是确切的时间,而是您可以获得的最佳近似值。 As with everything, the exact time is impossible to measure.与所有事情一样,无法测量确切的时间

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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