由于自己做的项目最近报了很多这个异常:org.apache.http.conn.ConnectionPoolTimeoutException: Timeout waiting for connection
所以研究了一下连接这方面的资料,总结以下几点:
httpClient 预防连接满了的方法:
1、设置最大连接数
static {
httpParams = new BasicHttpParams();
// 设置最大连接数
ConnManagerParams.setMaxTotalConnections(httpParams, 600);
// 设置获取连接的最大等待时间
ConnManagerParams.setTimeout(httpParams, 60000);
// 设置每个路由最大连接数
ConnPerRouteBean connPerRoute = new ConnPerRouteBean(300);
ConnManagerParams.setMaxConnectionsPerRoute(httpParams,connPerRoute);
// 设置连接超时时间
HttpConnectionParams.setConnectionTimeout(httpParams, 10000);
// 设置读取超时时间
HttpConnectionParams.setSoTimeout(httpParams, 10000);
2、每个请求之后关闭连接
public static String readNet (String urlPath)
{
StringBuffer sb = new StringBuffer ();
HttpClient client = null;
InputStream in = null;
InputStreamReader isr = null;
HttpGet get = new HttpGet();
try
{
client = HttpConnectionManager.getHttpClient();
get.setURI(new URI(urlPath));
HttpResponse response = client.execute(get);
if (response.getStatusLine ().getStatusCode () != 200) {
get.abort();
return null;
}
HttpEntity entity =response.getEntity();
if( entity != null ){
in = entity.getContent();
......
}
return sb.toString ();
}
catch (Exception e)
{
get.abort();
e.printStackTrace ();
return null;
}
finally
{
if (isr != null){
try
{
isr.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
}
if (in != null){
try
{
in.close ();
}
catch (IOException e)
{
e.printStackTrace ();
}
}
}
}
3、设置tomcat的连接数
1、修改最大连接数,在/opt/probe/patrol/tomcat_plan_5535/conf/server.xml中
<Connector port="80" maxHttpHeaderSize="8192"
maxThreads="600" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />
参考资料:
http://www.haogongju.net/art/1928653
HttpClient连接池原理及一次连接时序图
http://blog.csdn.net/shootyou/article/details/6615051
http://my.eoe.cn/530696/archive/10540.html
HttpClient详解(二)
http://www.2cto.com/os/201303/193008.html
Linux下查看tcp连接数及状态
设置tomcat的连接数
http://www.blogjava.net/wangxinsh55/archive/2012/07/16/383209.html --这边文章讲解了HTTPClient4的连接机制,很清晰