远程调用----HttpClient连接池

学连接池首先要明白:

    1.http连接池也不是万能的,过多的长连接会占用服务器资源,导致其他服务受阻

    2.http连接池值适用于请求是经常访问同一主机(或同一接口)的情况下

    3.并发数不高的情况下资源利用率低下

如何使用http连接池提高服务器性能??

    1. 使用 HttpClients.custom()可以构建自定义CloseableHttpClient 对象

            setConnectionManager  用于配置连接

            setDefaultRequestConfig  用于配置请求

    2.通过PoolingHttpClientConnectionManger对象 可以为连接配置连接数 和 并发数

            setMaxTotal(数值);   设置最大连接数

            setDefaultMaxPerRoute(数值);  设置并发访问数

  3. 通过 RequestConfig.custom() 可以配置各种超时时间

 

@Test
public void testDemo01() throws IOException {
    //1 配置连接管理
    PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager();
    // 1.1 设置最大连接数
    connectionManager.setMaxTotal(1000);
    // 1.2 设置并发访问数
    connectionManager.setDefaultMaxPerRoute(20);

    //2 请求配置
    RequestConfig requestConfig = RequestConfig.custom()
            .setConnectTimeout(1000)
            .setConnectionRequestTimeout(500)
            .setSocketTimeout(10 * 1000)
            .build();

    // 3 获得工具类
    CloseableHttpClient httpClient = HttpClients.custom()
            .setConnectionManager(connectionManager)
            .setDefaultRequestConfig(requestConfig)
            //重定向策略
            .setRedirectStrategy(new LaxRedirectStrategy())
            .build();

    // 4 发送请求
    CloseableHttpResponse response = null;
    try {
        HttpGet httpGet = new HttpGet("http://localhost:9090/user");

        response = httpClient.execute(httpGet);

        if(response.getStatusLine().getStatusCode() == 200){
            String str = EntityUtils.toString(response.getEntity(),"UTF-8");
            System.out.println(str);
        }
    } catch (IOException e) {
        e.printStackTrace();
    } finally {
        response.close();
    }