目录
使用MultiThreadedHttpConnectionManager来配置线程池连接数量等等。
实例
MultiThreadedHttpConnectionManager connectionManager =
new MultiThreadedHttpConnectionManager();
HttpClient客户端=新的HttpClient(connectionManager);
...
//然后从执行方法的某个线程内部
GetMethod get = new GetMethod(“http://httpcomponents.apache.org/”);
尝试{
client.executeMethod(get);
//打印对stdout
System.out.println的响应(get.getResponseBodyAsStream());
} finally {
//确保连接被释放回连接
// manager
get.releaseConnection();
}
参数
MultiThreadedHttpConnectionManager支持以下选项:
connectionStaleCheckingEnabled | 该connectionStaleCheckingEnabled标志上的所有创建的连接设置。除特殊情况外,该值应保留为真。有关 更多详细信息,请参阅 HttpConnection文档。 |
maxConnectionsPerHost | 将为任何特定HostConfiguration创建的最大连接数。默认为2。 |
maxTotalConnections | 最大活动连接数。默认为20。 |
配置重要参数
有两个重要参数:MaxTotalConnections,MaxConnectionsPerHost(默认为2)
这两个参数同时影响连接数大小,如果只配置一个参数的话,会导致总连接数为2->MaxConnectionsPerHost
导致问题
n多连接上来而无法从ConnectManager中获取连接,导致很多线程阻塞,占用端口
源码
正确的事例
final String url= "http://www.taobao.com" ;
final HttpClient client = new HttpClient();
final MultiThreadedHttpConnectionManager connectionManager = new
MultiThreadedHttpConnectionManager();
connectionManager.setMaxTotalConnections (1);//总的连接数
connectionManager.setMaxConnectionsPerHost (2);//每个host的最大连接数
client.setHttpConnectionManager( connectionManager );
httpclient官网