问题描述
我正在尝试在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连接池实现正确吗?
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连接池中的连接收回策略的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!