代码是前辈写的,在对代码进行压测的时候遇到了个问题,最大线程是 不能超过setDefaultMaxPerRoute设置的数字,一点超过 就会死掉。这里会报错 connection pool shut down httpclient
查找过很多博客,查到原因是因为接受到的集合没有释放导致 CloseableHttpClient 一直在被占用。随意可使用的最线程数 就不会超过 之前设置setDefaultMaxPerRoute 数字
private
static
CloseableHttpClienthttpClient;
static
{
PoolingHttpClientConnectionManagercm =
new
PoolingHttpClientConnectionManager();
cm.setMaxTotal(
200
);
cm.setDefaultMaxPerRoute(
20
);
cm.setDefaultMaxPerRoute(
50
);
httpClient = HttpClients.custom().setConnectionManager(cm).build();
}
public
static
String get(String url) {
HttpResponse response
=
null
;
BufferedReaderin =
null
;
String result =
""
;
try
{
HttpGethttpGet =
new
HttpGet(url);
response = httpClient.execute(httpGet);
in =
new
BufferedReader(
new
InputStreamReader(response.getEntity().getContent()));
StringBuffersb =
new
StringBuffer(
""
);
String line =
""
;
String NL = System.getProperty(
"line.separator"
);
while
((line = in.readLine()) !=
null
) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}
catch
(IOException e) {
e.printStackTrace();
}
return
result;
}
public
static
void
main(String[] args) {
}
}
这里出现的错误就是 使用接受 httpClient.execute(httpGet); 的返回集合是错误的
应该使用 CloseableHttpResponse 并且需要关闭 接收到的返回结合
正确的写法:
public
static
String get(String url) {
CloseableHttpResponse response
=
null
;
BufferedReaderin =
null
;
String result =
""
;
try
{
HttpGethttpGet =
new
HttpGet(url);
response = httpClient.execute(httpGet);
in =
new
BufferedReader(
new
InputStreamReader(response.getEntity().getContent()));
StringBuffersb =
new
StringBuffer(
""
);
String line =
""
;
String NL = System.getProperty(
"line.separator"
);
while
((line = in.readLine()) !=
null
) {
sb.append(line + NL);
}
in.close();
result = sb.toString();
}
catch
(IOException e) {
e.printStackTrace();
}
finally
{
try
{
if
(
null
!= response) response.close();
}
catch
(IOException e) {
e.printStackTrace();
}
}
return
result;
}
return
result;
}
public
static
void
main(String[] args) {
}
}
这样问题就完美解决了