package com.lantone.qc.trans.util.http;

import org.apache.http.HttpHost;
import org.apache.http.conn.routing.HttpRoute;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;

/**
 * 
 * ClassName: HttpConnectionManager 
 * Function: HTTP连接池 
 * date: 2015年7月10日 下午10:50:48  
 * 
 * @author 楼辉荣(Fyeman) 
 * @version 1.0 
 * @since JDK 1.7
 */
public class HttpConnectionManager {
	private static Logger log = LoggerFactory.getLogger(HttpConnectionManager.class);
	private static PoolingHttpClientConnectionManager cm;
	static {
		try {
			cm = new PoolingHttpClientConnectionManager();
		    // 将最大连接数增加到200
		    cm.setMaxTotal(200);
		    // 将每个路由基础的连接增加到20
		    cm.setDefaultMaxPerRoute(20);
		    //将目标主机的最大连接数增加到50
		    HttpHost localhost = new HttpHost("http://115.28.138.12", 7070);
		    cm.setMaxPerRoute(new HttpRoute(localhost), 50);
		} catch (Exception e) {
			log.error("初始化HTTP连接池出错", e);
		}
	}

	/**
	 * 
	 * @Title: getHttpClient
	 * @Description: HTTP链接池返回空闲链接
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @return 
	 * @since JDK 1.7
	 */
	public static CloseableHttpClient getHttpClient() throws Exception {
		try {
			CloseableHttpClient httpClient = HttpClients.custom().setConnectionManager(cm).build();
			return httpClient;
		} catch (Exception e) {
			log.error("获取CloseableHttpClient出错", e);
			throw e;
		}
	}
	
	/**
	 * 
	 * @Title: closeHttpClient
	 * @Description: HTTP放回链接
	 * 
	 * @author 楼辉荣(Fyeman) 
	 * @param httpClient 
	 * @since JDK 1.7
	 */
	public static void closeHttpClient(CloseableHttpClient httpClient) throws IOException {
		if (httpClient != null) {
			try {
				httpClient.close();
			} catch (IOException ioe) {
				log.error("关闭HTTP连接出错", ioe);
				throw ioe;
			}
		}
	}
}
