CloseableHttpClient,以及如何从连接池使用它?

问题描述

我为此池创建了一个connectionManager->>

    public static PoolingHttpClientConnectionManager getCm() {
        return cm;
    }

    public static void setCm(PoolingHttpClientConnectionManager cm) {
        ClassName.cm = cm;
    }

public static PoolingHttpClientConnectionManager createPool()
        {
            System.out.println("Generating new connection pool");
            setCm( new PoolingHttpClientConnectionManager());   
            getCm().setMaxTotal(10);
            getCm().setDefaultMaxPerRoute(5);
            return getCm();
        }

我正在使用此->>

创建CloseableHttpClient的实例
    public static CloseableHttpClient createConnection(){
            if(getCm()!=null)
                return  HttpClients.custom().setConnectionManager(getCm()).setConnectionManagerShared(true).setDefaultRequestConfig(getConfig()).build();
            else
                return HttpClients.custom().setConnectionManager(createPool()).setConnectionManagerShared(true).setDefaultRequestConfig(getConfig()).build();
        }

但是在这里每次我使用PoolingHttpClientConnectionManager创建CloseableHttpClient的实例。如果这是正确的方法,我会感到困惑吗?

在我进行HTTP调用的类中,我是以这种方式进行的--- >>

private static CloseableHttpClient client;   //class level variable. static or final? Which one to prefer? I want this to handle more than 50 concurrent request

Inside My method--->>

client = createConnection();

String endPoint = //someendpoint 
HttpPost httpPost = new HttpPost(endPoint);
httpPost.setHeader("Content-type","application/json");
httpPost.setHeader("Accept-API-Version","resource=2.0,protocol=1.0");


CloseableHttpResponse response1 = null;
        try{
             response1 =  client.execute(httpPost);
                String responseString;
                int statusCode;
                responseString = EntityUtils.toString(response1.getEntity());
         //doing something useful
         }catch(){
          
          } finally(){           //Another big question comes here. How to close and what should I close?
                                 /Just to be on the safe side,I am closing everything
           httpPost.releaseConnection();
           if(response1!= null)
                        response1.close();
           if (client != null)
                        client.close();
        

         }

请提出最佳方法或替代方法?我也是新手,这样做是为了学会宽恕并纠正我(如果我犯了任何错误)。

解决方法

暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!

如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。

小编邮箱:dio#foxmail.com (将#修改为@)

相关问答

错误1:Request method ‘DELETE‘ not supported 错误还原:...
错误1:启动docker镜像时报错:Error response from daemon:...
错误1:private field ‘xxx‘ is never assigned 按Alt...
报错如下,通过源不能下载,最后警告pip需升级版本 Requirem...