2017-08-24 60 views
0

在我的项目中,从另一个应用程序B调用特定的远程服务器A.应用程序B分布在X个节点上。应用程序B拥有一个创建PoolingHttpClientConnectionManager和HttpClient的地方。但是,HttpClient.execute()方法遍布应用程序B中的代码库。计数到apache的呼叫HttpClient

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

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

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

回答

2

尝试使用自定义的请求执行拦截代替协议拦截的

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();