我为池创建了一个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();
}
但在这里,每次我都使用PoolighttpClientConnectionManager创建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();
}
请建议最好的方法还是替代方法?我也是一个新手,这样做是为了学习,所以原谅和纠正我,如果我犯了任何错误。
暂无答案!
目前还没有任何答案,快来回答吧!