美文网首页
HttpClient 4.5.2-(五)连接池的配置

HttpClient 4.5.2-(五)连接池的配置

作者: 大漠知秋 | 来源:发表于2017-07-18 17:31 被阅读0次

紧接上一节,本节记录 【连接池的配置】
  两个主机建立连接的过程是很复杂的一个过程,涉及到多个数据包的交换,并且也很耗时间。Http连接需要的三次握手开销很大,这一开销对于比较小的http消息来说更大。但是如果我们直接使用已经建立好的http连接,这样花费就比较小,吞吐率更大。


修改代码

上节代码的基础上,我们添加全局静态变量连接池管理对象,提供静态代码块初始化连接池管理对象.

  • 初始化
......前省略

/**
 * Http请求工具类
 * 
 * @author 大漠知秋
 */
public class HttpRequestUtils {

    /** 全局连接池对象 */
    private static final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); 
    
    /**
     * 静态代码块配置连接池信息
     */
    static {
        
        // 设置最大连接数
        connManager.setMaxTotal(200);
        // 设置每个连接的路由数
        connManager.setDefaultMaxPerRoute(20);
        
    }
    
    /**
     * 获取Http客户端连接对象
     * 
     * @param timeOut 超时时间
     * @return Http客户端连接对象
     */
    public static CloseableHttpClient getHttpClient(Integer timeOut) {

......后省略

PoolingHttpClientConnectionManager是个复杂的类,它管理着连接池,可以同时为很多线程提供http连接请求。当请求一个新的连接时,如果连接池有可用的持久连接,连接管理器就会使用其中的一个,而不是再创建一个新的连接。

PoolingHttpClientConnectionManager维护的连接数在每个路由基础和总数上都有限制。默认,每个路由基础上的连接不超过2个,总连接数不能超过20。在实际应用中,这个限制可能会太小了,尤其是当服务器也使用Http协议时。此处我们设置为最高200个总连接数和每个基础路由连接不超过20个。

  • 已经在全局声明Http连接池管理工具,配置进httpClient连接客户端
/**
 * 获取Http客户端连接对象
 * 
 * @param timeOut 超时时间
 * @return Http客户端连接对象
 */
public static CloseableHttpClient getHttpClient(Integer timeOut) {
    // 创建Http请求配置参数
    RequestConfig requestConfig = RequestConfig.custom()
        // 获取连接超时时间
        .setConnectionRequestTimeout(timeOut)
        // 请求超时时间
        .setConnectTimeout(timeOut)
        // 响应超时时间
        .setSocketTimeout(timeOut)
        .build();
    
    /**
     * 测出超时重试机制为了防止超时不生效而设置
     *  如果直接放回false,不重试
     *  这里会根据情况进行判断是否重试
     */
    HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
        @Override
        public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
            if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                return false;
            }
            if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                return true;
            }
            if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                return false;
            }
            if (exception instanceof InterruptedIOException) {// 超时
                return true;
            }
            if (exception instanceof UnknownHostException) {// 目标服务器不可达
                return false;
            }
            if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                return false;
            }
            if (exception instanceof SSLException) {// ssl握手异常
                return false;
            }
            HttpClientContext clientContext = HttpClientContext.adapt(context);
            HttpRequest request = clientContext.getRequest();
            // 如果请求是幂等的,就再次尝试
            if (!(request instanceof HttpEntityEnclosingRequest)) {
                return true;
            }
            return false;
        }
    };
    
    // 创建httpClient
    return HttpClients.custom()
            // 把请求相关的超时信息设置到连接客户端
            .setDefaultRequestConfig(requestConfig)
            // 把请求重试设置到连接客户端
            .setRetryHandler(retry)
            // 配置连接池管理对象
            .setConnectionManager(connManager)
            .build();
}

在上方创建httpClient处把连接池管理对象配置到连接客户端中

  • 最后完整代码
package com.lynchj.writing;

import java.io.IOException;
import java.io.InterruptedIOException;
import java.net.UnknownHostException;

import javax.net.ssl.SSLException;
import javax.net.ssl.SSLHandshakeException;

import org.apache.http.HttpEntity;
import org.apache.http.HttpEntityEnclosingRequest;
import org.apache.http.HttpRequest;
import org.apache.http.NoHttpResponseException;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpRequestRetryHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.protocol.HttpClientContext;
import org.apache.http.conn.ConnectTimeoutException;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.impl.conn.PoolingHttpClientConnectionManager;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.EntityUtils;

/**
 * Http请求工具类
 * 
 * @author 大漠知秋
 */
public class HttpRequestUtils {

    /** 全局连接池对象 */
    private static final PoolingHttpClientConnectionManager connManager = new PoolingHttpClientConnectionManager(); 
    
    /**
     * 静态代码块配置连接池信息
     */
    static {
        
        // 设置最大连接数
        connManager.setMaxTotal(200);
        // 设置每个连接的路由数
        connManager.setDefaultMaxPerRoute(20);
        
    }
    
    /**
     * 获取Http客户端连接对象
     * 
     * @param timeOut 超时时间
     * @return Http客户端连接对象
     */
    public static CloseableHttpClient getHttpClient(Integer timeOut) {
        // 创建Http请求配置参数
        RequestConfig requestConfig = RequestConfig.custom()
            // 获取连接超时时间
            .setConnectionRequestTimeout(timeOut)
            // 请求超时时间
            .setConnectTimeout(timeOut)
            // 响应超时时间
            .setSocketTimeout(timeOut)
            .build();
        
        /**
         * 测出超时重试机制为了防止超时不生效而设置
         *  如果直接放回false,不重试
         *  这里会根据情况进行判断是否重试
         */
        HttpRequestRetryHandler retry = new HttpRequestRetryHandler() {
            @Override
            public boolean retryRequest(IOException exception, int executionCount, HttpContext context) {
                if (executionCount >= 3) {// 如果已经重试了3次,就放弃
                    return false;
                }
                if (exception instanceof NoHttpResponseException) {// 如果服务器丢掉了连接,那么就重试
                    return true;
                }
                if (exception instanceof SSLHandshakeException) {// 不要重试SSL握手异常
                    return false;
                }
                if (exception instanceof InterruptedIOException) {// 超时
                    return true;
                }
                if (exception instanceof UnknownHostException) {// 目标服务器不可达
                    return false;
                }
                if (exception instanceof ConnectTimeoutException) {// 连接被拒绝
                    return false;
                }
                if (exception instanceof SSLException) {// ssl握手异常
                    return false;
                }
                HttpClientContext clientContext = HttpClientContext.adapt(context);
                HttpRequest request = clientContext.getRequest();
                // 如果请求是幂等的,就再次尝试
                if (!(request instanceof HttpEntityEnclosingRequest)) {
                    return true;
                }
                return false;
            }
        };
        
        // 创建httpClient
        return HttpClients.custom()
                // 把请求相关的超时信息设置到连接客户端
                .setDefaultRequestConfig(requestConfig)
                // 把请求重试设置到连接客户端
                .setRetryHandler(retry)
                // 配置连接池管理对象
                .setConnectionManager(connManager)
                .build();
    }
    
    /**
     * GET请求
     * 
     * @param url 请求地址
     * @param timeOut 超时时间
     * @return
     */
    public static String httpGet(String url, Integer timeOut) {
        String msg = "-1";
        
        // 获取客户端连接对象
        CloseableHttpClient httpClient = getHttpClient(timeOut);
        // 创建GET请求对象
        HttpGet httpGet = new HttpGet(url);
        
        CloseableHttpResponse response = null;
        
        try {
            // 执行请求
            response = httpClient.execute(httpGet);
            // 获取响应实体
            HttpEntity entity = response.getEntity();
            // 获取响应信息
            msg = EntityUtils.toString(entity, "UTF-8");
        } catch (ClientProtocolException e) {
            System.err.println("协议错误");
            e.printStackTrace();
        } catch (ParseException e) {
            System.err.println("解析错误");
            e.printStackTrace();
        } catch (IOException e) {
            System.err.println("IO错误");
            e.printStackTrace();
        } finally {
            if (null != response) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                } catch (IOException e) {
                    System.err.println("释放链接错误");
                    e.printStackTrace();
                }
            }
        }
        
        return msg;
    }
    
    public static void main(String[] args) {
        
        System.out.println(httpGet("http://www.baidu.com", 6000));
        
    }
    
}

本节完毕,下一节记录【安全的SSL/TLS连接-绕过证书】

相关文章

网友评论

      本文标题:HttpClient 4.5.2-(五)连接池的配置

      本文链接:https://www.haomeiwen.com/subject/tjmhkxtx.html