2014-10-02 105 views
2

如何測量我的應用程序的HttpClient帶寬使用情況? (HttpComponents 4.3)使用Apache HttpComponents測量帶寬使用情況HttpClient

我有一個使用HttpClient與服務器通信的客戶端應用程序。所有請求都是通過使用池化http連接管理器的相同客戶端完成的。不幸的是,大多數請求直接使用httpclient(不是全部),因此在請求位置測量帶寬是可行的,但是很痛苦。

在客戶端或連接管理器的構造函數中,我可以簡單地注入自己的帶寬監視器(還是已經構建在某個我沒有發現的地方)的地方?

我可以這樣做嗎?

HttpClientBuilder.create().addInterceptorLast(new HttpResponseInterceptor() 
    { 

     @Override 
     public void process(HttpResponse response, HttpContext context) throws HttpException, IOException 
     { 

     } 
    }).build(); 
+0

什麼是_exactly_你正試圖測量?傳輸的總字節數?每個連接傳輸的總字節數?每個請求的字節數?每秒? – oleg 2014-10-03 12:30:22

+0

整個客戶端的每秒總字節數(它將進行多個請求/連接/等)。 – Cogman 2014-10-03 15:32:20

回答

4

定製HttpRequestExecutor或許應該是最方便的攔截點

這是一種非常原始的解決方案,但我希望是足以讓你開始。

final AtomicLong totalBytes = new AtomicLong(); 

HttpRequestExecutor requestExecutor = new HttpRequestExecutor() { 

    @Override 
    protected HttpResponse doSendRequest(
      final HttpRequest request, 
      final HttpClientConnection conn, 
      final HttpContext context) throws IOException, HttpException { 
     HttpResponse response = super.doSendRequest(request, conn, context); 
     HttpConnectionMetrics metrics = conn.getMetrics(); 
     totalBytes.addAndGet(metrics.getSentBytesCount()); 
     metrics.reset(); 
     return response; 
    } 

    @Override 
    protected HttpResponse doReceiveResponse(
      final HttpRequest request, 
      final HttpClientConnection conn, 
      final HttpContext context) throws HttpException, IOException { 
     HttpResponse response = super.doReceiveResponse(request, conn, context); 
     HttpConnectionMetrics metrics = conn.getMetrics(); 
     totalBytes.addAndGet(metrics.getReceivedBytesCount()); 
     metrics.reset(); 
     return response; 
    } 
}; 

CloseableHttpClient httpclient = HttpClients 
     .custom() 
     .setRequestExecutor(requestExecutor) 
     .build();