HttpClient连接池的使用示例

public class PoolUtil {

    private static CloseableHttpClient httpClient;
    private static PoolingHttpClientConnectionManager poolingHttpClientConnectionManager;

    private static final int  MAX_CONN_TOTAL = 10;
    private static final int  MAX_CONN_PERROUTE = 10;

    static {
        poolingHttpClientConnectionManager = initPool();
    }

    public static HttpClient getHttpClient(){
        if(null != httpClient){
            return httpClient;
        }
        synchronized (PoolUtil.class){
            if(null == httpClient){
                httpClient = HttpClients.custom().setConnectionManager(poolingHttpClientConnectionManager).build();
                return httpClient;
            }
        }
        return httpClient;
    }

    private static PoolingHttpClientConnectionManager initPool(){
        PoolingHttpClientConnectionManager pool = new PoolingHttpClientConnectionManager();
        pool.setMaxTotal(MAX_CONN_TOTAL);
        pool.setDefaultMaxPerRoute(MAX_CONN_PERROUTE);
        return pool;
    }

    public static HttpResponse get(String url , RequestConfig config) throws Exception{
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);
        HttpClient client = getHttpClient();
        return client.execute(httpGet);
    }

    public static HttpResponse get(String url) throws Exception{
        RequestConfig config = RequestConfig.custom()
                .setConnectionRequestTimeout(500)
                .setConnectTimeout(3000)
                .setSocketTimeout(3000)
                .build();
        HttpGet httpGet = new HttpGet(url);
        httpGet.setConfig(config);
        return getHttpClient().execute(httpGet);
    }
}

 

你可能感兴趣的:(Java)