我想计算每个请求请求开始和建立连接(TCP 连接建立)之间的时间。
我问了这个问题question但它是模棱两可的。
我查看了建议的答案,也许我误解了,但我知道 Connection.Listener 至少在全局范围内工作(总体连接时间)
所以我尝试了基于SocketAddressResolver的方法:
private static class CustomSocketAddressResolver implements SocketAddressResolver {
private StopWatch stopWatch = new StopWatch();
private SocketAddressResolver adaptee;
public CustomSocketAddressResolver(SocketAddressResolver adaptee) {
this.adaptee = adaptee;
}
public long getConnectTime() {
return stopWatch.getTime();
}
@Override
public void resolve(String host, int port, Promise<List<InetSocketAddress>> promise) {
stopWatch.reset();
stopWatch.start();
adaptee.resolve(host, port, new Promise<List<InetSocketAddress>>() {
@Override
public void succeeded(List<InetSocketAddress> result) {
// Add as first address an invalid address so that we test
// that the connect operation iterates over the addresses.
stopWatch.stop();
promise.succeeded(result);
}
@Override
public void failed(Throwable x) {
stopWatch.stop();
promise.failed(x);
}
});
}
}
然后我可以获得这样的连接时间:
((CustomSocketAddressResolver) httpClient.getSocketAddressResolver()).getConnectTime()
确实有效,但是有更好的方法吗?
最佳答案
I want to compute per request the time between the begining of request and time connection is established (TCP connection establishment).
这里可能存在误解。
HTTP/1.1 和 HTTP/2 使用持久 TCP 连接。 TCP 连接被创建、保持打开状态并重用于许多请求。
例如,创建一个 TCP 连接,然后将其重新用于 1067 个请求,然后仍然保持打开状态。
计算第 1067 个请求开始与首次建立连接之间的时间没有多大意义(或者我很想听听这方面的用例)。
我知道连接保持开放数天的情况。
关于java - 如何使用 Jetty 客户端获取基于请求的连接所花费的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/66608173/