0
我正在尝试在java中为web服务实现http连接池。该服务将收到一个请求,然后调用其他http服务。Java中Http连接池中的连接驱逐策略
public final class HttpClientPool {
private static HttpClientPool instance = null;
private PoolingHttpClientConnectionManager manager;
private IdleConnectionMonitorThread monitorThread;
private final CloseableHttpClient client;
public static HttpClientPool getInstance() {
if (instance == null) {
synchronized(HttpClientPool.class) {
if (instance == null) {
instance = new HttpClientPool();
}
}
}
return instance;
}
private HttpClientPool() {
manager = new PoolingHttpClientConnectionManager();
client = HttpClients.custom().setConnectionManager(manager).build();
monitorThread = new IdleConnectionMonitorThread(manager);
monitorThread.setDaemon(true);
monitorThread.start();
}
public CloseableHttpClient getClient() {
return client;
}
}
class IdleConnectionMonitorThread extends Thread {
private final HttpClientConnectionManager connMgr;
private volatile boolean shutdown;
IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
super();
this.connMgr = connMgr;
}
@Override
public void run() {
try {
while (!shutdown) {
synchronized(this) {
wait(5000);
// Close expired connections
connMgr.closeExpiredConnections();
// Optionally, close connections
// that have been idle longer than 30 sec
connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
}
}
} catch (InterruptedException ex) {
//
}
}
void shutdown() {
shutdown = true;
synchronized(this) {
notifyAll();
}
}
}
正如Connection Management文档中提到的连接驱逐策略,而不是使用
IdleConnectionMonitorThread
如果我使用manager.setValidateAfterInactivity
什么的。以上两种方法的优缺点是什么&?上述Http连接池实现是否正确?
在我发布在我的问题https://hc.apache.org/httpcomponents-client-ga/tutorial/html/connmgmt.html#d5e418的链接中。它被提及'陈旧的连接检查不是100%可靠的。每个套接字模型不包含一个用于空闲连接的线程的唯一可行解决方案是专用监视器线程。那么这也适用于'setValidateAfterInactivity'吗? – tuk
是的,它的确如此。鉴于过时的连接检查相对昂贵HttpClient从4.4版开始不再检查每个连接,而只检查那些在一段时间内处于非活动状态的连接 – oleg
如果我正确设置'setValidateAfterInactivity',将运行过期检查如果连接在'setValidateAfterInactivity'中指定的那么多毫秒,即使它不是可靠的。如果我们想要完全可靠,那么我们应该使用'IdleMonitorThread'方法? – tuk