1

我有一个为池创建一个连接管理器,因为 -->>

    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();
        

         }

请建议最好的方法或替代方法?我也是一个新手,这样做是为了学习,如果我犯了任何错误,请原谅并纠正我。

4

0 回答 0