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

时间:2017-02-24 12:43:25

标签: java connection-pooling apache-httpclient-4.x

我正在尝试在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 doc中提到的连接驱逐策略,而不是使用IdleConnectionMonitorThread如果我使用manager.setValidateAfterInactivity。什么是专业人士和上述两种方法的缺点?

  2. 上述Http连接池实现是否正确?

2 个答案:

答案 0 :(得分:1)

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

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

答案 1 :(得分:0)

在HttpClient 4.5.3中,manager.setValidateAfterInactivity的defult值为2000,即2秒。因此,我建议不要使用IdleConnectionMonitorThread,除非您希望应用程序验证不活动的连接并同时进行清理。