由于自己做的项目最近报了很多这个异常: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中
maxThreads="600" minSpareThreads="25" maxSpareThreads="75"
enableLookups="false" redirectPort="8443" acceptCount="100"
connectionTimeout="20000" disableUploadTimeout="true" URIEncoding="UTF-8" />