Java Http 连接池中的连接驱逐策略 [英] Connection Eviction strategy in Http Connection Pooling in Java
问题描述
我正在尝试在 Java 中为 Web 服务实现 http 连接池.该服务将收到一个请求,然后调用其他 http 服务.
I am trying to implement a http connection pooling in java for a web service. The service will receive a request and then call other http services.
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();
}
}
}
如连接管理中所述 连接驱逐策略的文档,而不是使用
IdleConnectionMonitorThread
如果我使用manager.setValidateAfterInactivity
会怎样.什么是优点 &以上两种方法的缺点?
As mentioned in Connection Management doc for Connection Eviction strategy instead of using a
IdleConnectionMonitorThread
what if I usemanager.setValidateAfterInactivity
. What are the pros & cons of the above two approach?
上面的Http Connection Pool实现是否正确?
Is the above Http Connection Pool implementation correct?
推荐答案
如果 #setValidateAfterInactivity
设置为正值,持久连接将在租用请求时得到验证.也就是说,在尝试重新使用它们之前,陈旧和不可重用的连接不会自动从池中逐出.
With #setValidateAfterInactivity
set to a positive value persistent connections will get validated upon lease request. That is, stale and non-reusable connections will not get automatically evicted from the pool until an attempt is made to re-use them.
运行一个专用线程,以指定的时间间隔迭代持久连接并从池中删除过期或空闲的连接,以增加额外的线程和略高的池锁争用为代价确保主动连接驱逐.
Running a dedicated thread that iterates over persistent connections at the specified time interval and removes expired or idle connections from the pool ensures proactive connection eviction at the cost of an extra thread and slightly higher pool lock contention.
这篇关于Java Http 连接池中的连接驱逐策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!