javahttpjettyhttp2jetty-9

How to get the time it took to connect using Jetty Client


I am using Jetty Client 11 and would like to compute the time it takes to establish connection.

I am using High Level HttpClient . I have read this documentation but I don't see any information on how to do that:

My guess is that this information is in Connection#onOpen but I don't see how to plug my code

ClientConnector connector = new ClientConnector();
connector.setConnectTimeout(Duration.ofSeconds(1));
connector.setIdleTimeout(Duration.ofSeconds(1));
ClientConnectionFactory.Info http1 = HttpClientConnectionFactory.HTTP11;

HTTP2Client http2Client = new HTTP2Client(connector);
ClientConnectionFactoryOverHTTP2.HTTP2 http2 = new 
          ClientConnectionFactoryOverHTTP2.HTTP2(http2Client);
HttpClientTransportDynamic transport = new HttpClientTransportDynamic(connector, http2, http1);

HttpClient httpclient = new HttpClient(transport);

QueuedThreadPool threadPool = new QueuedThreadPool(3);
threadPool.setName("test");
httpClient.setExecutor(threadPool);
httpClient.start();

Solution

  • It depends on what you mean by "establish connection".

    If you mean just TCP connection establishment, you may want to wrap/subclass the SocketAddressResolver and wrap/override resolve(host, port, promise).

    You can easily save the start time when resolve() is called, and record the stop time when the promise is completed.

    Alternatively you can add a Connection.Listener as a bean to HttpClient:

    HttpClient httpclient = new HttpClient(transport);
    httpClient.addBean(new Connection.Listener() {
      @Override
      public void onOpened(Connection connection) { 
        ... 
      }
    });
    

    If you mean TCP connection establishment + TLS handshake, you can use an SslHandshakeListener to know when the TLS handshake is completed, also adding it as a bean:

    HttpClient httpclient = new HttpClient(transport);
    httpClient.addBean(new SslHandshakeListener() {
      @Override
      public void handshakeSucceeded(Event event) {
        ...
      }
    });
    

    Look also at org.eclipse.jetty.io.ConnectionStatistics and IncludeExcludeConnectionStatistics for utility classes that records a number of statistics about connections.