[英]Measure bandwidth usage with Apache HttpComponents HttpClient
How can I measure HttpClients bandwidth usage for my app?如何测量我的应用程序的 HttpClients 带宽使用情况? (HttpComponents 4.3) (HttpComponents 4.3)
I have a client application that is communicating with a server using HttpClient.我有一个使用 HttpClient 与服务器通信的客户端应用程序。 All requests are done through the same client using a pooling http connection manager.所有请求都是使用池化 http 连接管理器通过同一个客户端完成的。 Unfortunately, most of the requests use the httpclient directly (not all of them) so measuring bandwidth at the request location would be doable, but a pain.不幸的是,大多数请求直接使用 httpclient(不是全部),因此在请求位置测量带宽是可行的,但很痛苦。
Is there a place at either the constructor of the client or the connection manager where I can simply inject my own bandwidth monitor (or is that already built in somewhere that I haven't discovered)?在客户端的构造函数或连接管理器中是否有一个地方可以简单地注入我自己的带宽监视器(或者它是否已经内置在我没有发现的地方)?
Can I do it with this?我可以用这个做吗?
HttpClientBuilder.create().addInterceptorLast(new HttpResponseInterceptor()
{
@Override
public void process(HttpResponse response, HttpContext context) throws HttpException, IOException
{
}
}).build();
Custom HttpRequestExecutor
should probably the most convenient interception point自定义HttpRequestExecutor
应该是最方便的拦截点
This is a very crude solution but I hope is enough to get you started.这是一个非常粗略的解决方案,但我希望足以让您入门。
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();
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 hold everything you need. HttpConnectionMetrics 包含您需要的一切。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.