在HttpClient之前我们有一个线程正在进行,它检查是否有MAX_TOTAL_CONNECTIONS到达。它看起来像这样:
@Override
public void run() {
try {
while (!shutdown) {
synchronized (this) {
wait(60000);
// this is an emergency check. if all connections have been exhausted, then shutdown the old connection manager and instantiate a new http client
PoolingHttpClientConnectionManager tsc = (PoolingHttpClientConnectionManager) connMgr;
// previously here was : tsc.getConnectionsInPool() == MAX_TOTAL_CONNECTIONS
// since the PoolingClientConnectionManager has no clear replacement multiple candidates:
// 1. tsc.getTotalStats().getLeased() (number of persistent connections tracked by the connection manager currently being used to execute requests.) (Available + Leased)
// 2. tsc.getTotalStats().getPending() (number of connection requests being blocked awaiting a free connection.)
// 3. tsc.getTotalStats().getAvailable() (number idle persistent connections.)
// 4. tsc.getTotalStats().getMax() (maximum number of allowed persistent connections.)
// because of the statement: The total number of connections in the pool is equal to available plus leased - will go to use the sum of them both.
PoolStats poolStats = tsc.getTotalStats();
if (poolStats.getAvailable() + poolStats.getLeased() == MAX_TOTAL_CONNECTIONS) {
System.out.println("Error in HttpClient: It seems as if all connections are exhausted: will create new HttpClient now!");
tsc.shutdown();
httpAgent = initializeDefaultHttpClient();
}
}
}
}
catch (InterruptedException ex) {
// terminate
}
catch (IOException e) {
// error
}
}
public void shutdown() {
shutdown = true;
synchronized (this) {
notifyAll();
}
}
}
现在我知道我们应该使用具有方法“.close()”的CloseableHttpClient。但是,我不会选择是否有可能检查我是否要关闭。
有人知道如何最好地解决这个问题吗?
THX
的Mac
答案 0 :(得分:1)
如果需要,绝对没有任何东西阻止你保持对底层连接池的引用
PoolingHttpClientConnectionManager cm = new PoolingHttpClientConnectionManager();
CloseableHttpClient client = HttpClients.custom()
.setConnectionManager(cm)
.build();
PoolStats totalStats = cm.getTotalStats();