使用Apache HttpComponents HttpClient测量带宽使用情况

时间:2014-10-02 17:45:39

标签: java apache-httpcomponents

如何衡量应用的HttpClients带宽使用情况? (HttpComponents 4.3)

我有一个使用HttpClient与服务器通信的客户端应用程序。所有请求都使用池化http连接管理器通过同一客户端完成。不幸的是,大多数请求直接使用httpclient(不是全部),因此在请求位置测量带宽是可行的,但很痛苦。

在客户端的构造函数或连接管理器中是否有位置我可以简单地注入我自己的带宽监视器(或者是已经在我还没有发现的某个地方构建的)?

我可以用这个吗?

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

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

        }
    }).build();

2 个答案:

答案 0 :(得分:5)

自定义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();

答案 1 :(得分:0)

HttpClient client = HttpClients.createDefault();
HttpGet req = new HttpGet("https://www.google.com/");
HttpClientContext hcc = HttpClientContext.create();
HttpResponse res = client.execute(req, hcc);
HttpConnectionMetrics metrics = hcc.getConnection().getMetrics();
EntityUtils.consumeQuietly(res.getEntity());
LOG.debug("sent: {}, recv: {}, reqcnt: {}, rescnt: {}",
        metrics.getSentBytesCount(), metrics.getReceivedBytesCount(),
        metrics.getRequestCount(), metrics.getResponseCount());

HttpConnectionMetrics包含您所需的一切。