Apache HttpComponents Client Instrumentation

This section requires usage of Apache HttpComponents Client at least in version 5.

Apache HttpComponents Client is an HTTP/1.1 compliant HTTP agent implementation.

Below you can find an example of how to instrument Apache HttpComponents Client Micrometer Observation. That means that depending on your Observation Handler configuration you instrument once, and can have multiple benefits out of it (e.g. metrics, distributed tracing).

Example of classic, blocking HTTP client.

// Setting up instrumentation (you need to create a client from the builder)
HttpClientBuilder clientBuilder = HttpClients.custom()
    .setRetryStrategy(retryStrategy)
    .addExecInterceptorLast("micrometer", new ObservationExecChainHandler(observationRegistry))
    .setConnectionManager(PoolingHttpClientConnectionManagerBuilder.create()
        .setDefaultConnectionConfig(connectionConfig)
        .build());

// Usage example
try (CloseableHttpClient client = classicClient()) {
    executeClassic(client, new HttpGet(server.baseUrl()));
}
assertThat(observationRegistry).hasObservationWithNameEqualTo(DEFAULT_METER_NAME)
    .that()
    .hasLowCardinalityKeyValue(OUTCOME.withValue("SUCCESS"))
    .hasLowCardinalityKeyValue(STATUS.withValue("200"))
    .hasLowCardinalityKeyValue(METHOD.withValue("GET"));

Example of async HTTP client.

// Setting up instrumentation (you need to create a client from the builder)
HttpAsyncClientBuilder clientBuilder = HttpAsyncClients.custom()
    .addExecInterceptorLast("micrometer", new ObservationExecChainHandler(observationRegistry))
    .setRetryStrategy(retryStrategy)
    .setConnectionManager(PoolingAsyncClientConnectionManagerBuilder.create()
        .setDefaultConnectionConfig(connectionConfig)
        .build());

// Usage example
try (CloseableHttpAsyncClient client = asyncClient()) {
    SimpleHttpRequest request = SimpleRequestBuilder.get(server.baseUrl()).build();
    executeAsync(client, request);
}
assertThat(observationRegistry).hasObservationWithNameEqualTo(DEFAULT_METER_NAME)
    .that()
    .hasLowCardinalityKeyValue(OUTCOME.withValue("SUCCESS"))
    .hasLowCardinalityKeyValue(STATUS.withValue("200"))
    .hasLowCardinalityKeyValue(METHOD.withValue("GET"));