我有以下使用 a 的代码PoolingClientConnectionManager
:
public static void main(String[] args) {
int NoOfSimultaneousRequest = 1000;
int poolsize =1000;
try{
if (poolsize>0){
mgr = new PoolingClientConnectionManager();
mgr.setMaxTotal(poolsize);
mgr.setDefaultMaxPerRoute(poolsize);
httpclient = new DefaultHttpClient(mgr);
}
Thread [] tr = new Thread[NoOfSimultaneousRequest];
for(int i=0;i<NoOfSimultaneousRequest;i++){
MultipleThreadsTest multiTest = new MultipleThreadsTest();
Thread t = new Thread(multiTest);
tr[i] = new Thread(multiTest);
}
for(int i=0;i<NoOfSimultaneousRequest;i++){
tr[i].start();
}
for(int i=0;i<NoOfSimultaneousRequest;i++){
tr[i].join();
}
}catch (Exception e){
e.printStackTrace();
}finally{
if (mgr!=null){
mgr.shutdown();
}
if (httpclient!=null){
httpclient.getConnectionManager().shutdown();
}
}
}
public void run() {
if (mgr==null){ //if no connection manager then create multiple instances of defaulthttpClient
HttpClient hc = new DefaultHttpClient();
response = invokeWebService(hc,"http://urltoPost") ;
}else{ //if connection manager is used then use only one instance of httpclient
response = invokeWebService(httpclient,"http://urltoPost") ;
}
}
private static String invokeWebService(HttpClient httpClient,String url){
HttpPost httpPost = new HttpPost(new URI(url));
try{
String response = httpClient.execute(httpPost,new BasicResponseHandler());
return response;
}catch(Exception e){
}finally{
if (httpPost != null) {
httpPost.releaseConnection();
}
}
}
我的问题是,当我关闭池(通过设置<= 0)时,与池打开( > 0)poolSize
相比,代码的执行速度要快得多。poolSize
这两个版本之间的唯一区别是,当使用池时,只有一个HttpClient
created 实例(如 Apache 推荐的那样),而当池关闭时,HttpClient
会创建多个实例。当我使用 HTTP 连接池时,代码应该执行得更好。但这并没有发生。你看到我使用连接管理器有什么问题吗?