提问者:小点点

使用PoolingHttpClientConnectionManager获取重用连接的统计信息


如何从PoolingHttpClientConnectionManager获取重用连接的数量?

它包含返回PoolStats的getTotalStats()方法,但不存在有关重用连接量的信息。

PoolingHttpClientConnectionManager有一个CPool的私有实例,它从http组件核心扩展了AbstractConnPool。当连接被重用时,getPoolEntryBlock方法调用可用于此目的的onReuse(entry)方法。

我看不出有什么方法可以获取这些信息用于监控目的。有人看到另一种选择吗?


共2个答案

匿名用户

如果您扩展或修饰标准池连接管理器,它应该为您提供收集所需连接重用详细信息的切入点

public class MyPoolingHttpClientConnectionManager extends PoolingHttpClientConnectionManager {

    final AtomicLong reusedCount = new AtomicLong();

    @Override
    protected HttpClientConnection leaseConnection(
            Future<CPoolEntry> future,
            long timeout,
            TimeUnit timeUnit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
        HttpClientConnection conn = super.leaseConnection(future, timeout, timeUnit);
        if (conn.isOpen()) {
            reusedCount.incrementAndGet();
        }
        return conn;
    }

}

匿名用户

解决方案是子类ConnectionRequest并覆盖get方法以将执行委托给构造函数上接收到的ConnectionRequest实例。

然后我覆盖来自PoolingHttpClientConnectionManager的request estConnection并将返回的ConnectionRequest与创建的子类包装起来。

如果连接打开,我会增加重用连接的统计信息。否则,我会增加创建的连接的统计信息。

public class MonitoredPoolingHttpClientConnectionManager extends PoolingHttpClientConnectionManager

    private final AtomicInteger createdConnections = new AtomicInteger();
    private final AtomicInteger reusedConnections = new AtomicInteger();

    @Override
    public ConnectionRequest requestConnection(HttpRoute route, Object state) {
        ConnectionRequest requestConnection = super.requestConnection(route, state);
        return new MonitoredConnectionRequest(requestConnection);
    }
    
    private class MonitoredConnectionRequest implements ConnectionRequest {

        private ConnectionRequest wrapped;

        public MonitoredConnectionRequest(ConnectionRequest requestConnection) {
            this.wrapped = requestConnection;
        }

        @Override
        public boolean cancel() {
            return wrapped.cancel();
        }

        @Override
        public HttpClientConnection get(long timeout, TimeUnit timeUnit) throws InterruptedException, ExecutionException, ConnectionPoolTimeoutException {
            HttpClientConnection conn = wrapped.get(timeout, timeUnit);
            if (conn.isOpen()) {
                reusedConnections.incrementAndGet();
            } else {
                createdConnections.incrementAndGet();
            }
            return conn;
        }
    }