计算对 apache HttpClient 的调用

Count calls to apache HttpClient

在我的项目中,一个特定的远程服务器A被另一个应用程序B调用。应用程序B分布在X个节点上。应用程序 B 在一个地方创建 PoolingHttpClientConnectionManager 和 HttpClient。然而,HttpClient.execute() 方法遍及应用程序 B 中的代码库。

出于遥测目的,我想跟踪每个 X 节点对远程服务器 A 发出的并发调用数。我正在使用 StatsD 客户端递增和递减计数器以跟踪调用。这个想法是在调用开始时增加一个计数器,并在调用成功、失败或超时时减少它。

我的第一个想法是使用 HttpRequestInterceptor 和 HttpResponseInterceptor 来递增和递减计数器。但是在超时的情况下,没有响应,因此 HttpResponseInterceptor 不会被调用。

有没有人有解决此问题的方法或更好的解决方案?我知道如果我们可以注释执行 HttpClient.execute() 的方法,问题会更简单,但是考虑到代码库的大小,这是一个昂贵的解决方案。因此,我正在寻找更好的选择。提前致谢。

尝试使用自定义请求执行拦截器而不是协议拦截器

final AtomicLong concurrentExchangeCount = new AtomicLong(0);

final HttpClientBuilder httpClientBuilder = new HttpClientBuilder() {

    @Override
    protected ClientExecChain decorateMainExec(final ClientExecChain mainExec) {
        return (route, request, clientContext, execAware) -> {
            concurrentExchangeCount.incrementAndGet();
            try {
                return mainExec.execute(route, request, clientContext, execAware);
            } finally {
                concurrentExchangeCount.decrementAndGet();
            }
        };
    }
};
final CloseableHttpClient httpClient = httpClientBuilder.build();