httpcomponents 4.3 Util

httpcomponents使用连接池时,如果使用默认的设置,一般情况下,服务端没有明确的申明keepalive的时间,于是乎连接池会把连接的keepalive时间默认为永久有效。


httpcomponents提供一个连接池的有效时间的设置策略,在没有明确的keepalive时间时我们可以自己设置一个超时时间:

ConnectionKeepAliveStrategy keepAliveStrategy = new DefaultConnectionKeepAliveStrategy() {
	@Override
	public long getKeepAliveDuration(
			HttpResponse response, HttpContext context) {
		long keepAlive = super.getKeepAliveDuration(response, context);
		if (keepAlive == -1) {
			// Keep connections alive 5000 milliseconds if a 5000 value has not be explicitly set by the server
			keepAlive = 5000;
		}
		return keepAlive;
	}
};


但实际上,httpcomponents的连接池并没有实现对超时连接的管理,只是提供了一个调用函数,使用者需要自己去实现一个线程去管理

public class IdleConnectionMonitorThread extends Thread{
	
	private final HttpClientConnectionManager connMgr;
    private static IdleConnectionMonitorThread _instance = null;
    private static Logger logger = LoggerFactory.getLogger(IdleConnectionMonitorThread.class);
    
    public static IdleConnectionMonitorThread instance(HttpClientConnectionManager connMgr){
    	if(_instance == null){  
            synchronized (IdleConnectionMonitorThread.class){  
                if(_instance == null){  
                    _instance = new IdleConnectionMonitorThread(connMgr);  
                }  
            }  
        }  
        return _instance;  
    }

    private IdleConnectionMonitorThread(HttpClientConnectionManager connMgr) {
        super();
        this.connMgr = connMgr;
    }

    @Override
    public void run() {
        try {
        	while (true) {
                synchronized (this) {
                    TimeUnit.SECONDS.sleep(5);
                    // 关闭失效的连接
                    connMgr.closeExpiredConnections();
                    // 可选的, 关闭60秒内不活动的连接
                    connMgr.closeIdleConnections(60, TimeUnit.SECONDS);
                }
            }
        } catch (InterruptedException ex) {
        	logger.info("IdleConnectionMonitorThread InterruptedException exits!");
        }
    }

}


然后自己在程序中开启线程维护连接池的超时等策略,否侧连接池中就会出现许多服务器实际上已经断开,但是httpclient这边还维护着这个无效的Http连接的问题,当我们的请求拿到这些无效连接使用时,failed!

你可能感兴趣的:(http,httpcomponents,4.3)