HttpClient解读(4)-验证释放连接的操作

阅读更多

dd

为了验证之前关闭连接的操作,写了如下代码:

public static void main(String[] args) throws IOException, InterruptedException {
	
	PoolingHttpClientConnectionManager manager = new PoolingHttpClientConnectionManager(100000L, TimeUnit.SECONDS);//指定一个连接的生存时间最大为100秒。
	manager.setDefaultMaxPerRoute(1);//指定一个router缓存的最大的连接数为1
	
	RequestConfig requestConfig = RequestConfig.custom().setConnectionRequestTimeout(10000)/*从连接池中取连接的超时时间。*/.setConnectTimeout(3000)/*建立连接的*/
			.setSocketTimeout(5000)/*包的最大间隔时间*/.build();
	
	HttpClientBuilder create = HttpClientBuilder.create();
	create.setConnectionManager(manager);
	create.setDefaultRequestConfig(requestConfig);
        create.evictExpiredConnections();//关闭失效的连接
	create.evictIdleConnections(1000*60L*3, TimeUnit.MILLISECONDS);//关闭长时间不用的连接
	
	final CloseableHttpClient httpClient = create.build();
		
	final HttpGet httpGet1 = new HttpGet("http://www.baidu.com");
	Thread t1 = new Thread(new Runnable() {//新线程进行连接,使用第一个连接,
		
		@Override
		public void run() {
			
			try {
				CloseableHttpResponse execute = httpClient.execute(httpGet1);
				StatusLine statusLine = execute.getStatusLine();
				int statusCode = statusLine.getStatusCode();
				if(statusCode == HttpStatus.SC_OK) {
					System.out.println("第一个请求成功,sleeep 3秒");
					Thread.sleep(3000L);
					System.out.println("第一个请求醒来");
//					EntityUtils.consume(execute.getEntity());//这是一个开关,第一次不注释,第二次注释掉
				} else {//不是200,关闭连接
					execute.close();
				}
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			} catch (InterruptedException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			
		}
	});
	t1.start();//启动第一个线程
	
	Thread.sleep(1000L);//睡眠1秒,保证第一个线程优先使用开辟的连接	
	
	final HttpGet httpGet2 = new HttpGet("http://www.baidu.com");
	CloseableHttpResponse execute = httpClient.execute(httpGet2);
	StatusLine statusLine = execute.getStatusLine();
	int statusCode = statusLine.getStatusCode();
	if(statusCode == HttpStatus.SC_OK) {
		System.out.println("第二个请求成功,sleeep 3秒");
		EntityUtils.consume(execute.getEntity());
	} else {//不是200,关闭连接
		execute.close();
	}
	
	httpClient.close();
		
}

 

 试验发现,当不注释掉那个EntityUtils.consume的时候是不会出现超时错误的,当注释掉之后就会出现Timeout waiting for connection from pool错误,所以可以确定,使用EntityUtils.consume的确是可以将连接还回连接池。

你可能感兴趣的:(EntityUtils,释放连接)