gpt4 book ai didi

java - Java中Http连接池中的连接驱逐策略

转载 作者:行者123 更新时间:2023-12-01 08:50:17 24 4
gpt4 key购买 nike

我正在尝试在 java 中为 Web 服务实现 http 连接池。该服务将接收请求,然后调用其他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();
}
}
}
  1. Connection Management 中所述连接驱逐策略的文档,而不是使用 IdleConnectionMonitorThread 如果我使用 manager.setValidateAfterInactivity 会怎样。以上两种方法各有什么优缺点?

  2. 上面的 Http 连接池实现正确吗?

最佳答案

#setValidateAfterInactivity 设置为正值,持久连接将根据租用请求进行验证。也就是说,过时的和不可重用的连接不会自动从池中逐出,直到尝试重新使用它们为止。

运行一个专用线程,以指定的时间间隔迭代持久连接,并从池中删除过期或空闲的连接,可确保主动驱逐连接,但代价是额外的线程和稍高的池锁争用。

关于java - Java中Http连接池中的连接驱逐策略,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42438970/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com