我有以下使用 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();
}
}
}
我的问题是,当我关闭池(通过设置 poolSize
<= 0)时,代码执行速度比打开池(poolSize
> 0)快得多.这两个版本之间的唯一区别是,当使用池时,只创建一个 HttpClient
实例(按照 Apache 的建议),当池关闭时,HttpClient
的多个实例> 已创建。当我使用 HTTP 连接池时,代码应该会执行得更好。但这并没有发生。您是否发现我使用连接管理器有任何问题?
最佳答案
您不能据此做出任何有效且受支持的诊断。为了找出您的应用程序运行得更快/更慢的原因,您需要收集信息,为此您需要进行性能测试。否则你只会在黑暗中射击。
对于您的案例,我会在您的测试期间开始测量整体系统性能,确保两个测试案例都使用相同类型的工作负载。
我所说的整体系统性能是指 CPU 和内存的利用率、饱和度和错误率。您需要找出代码执行时间的去向,并从那里开始更深入地挖掘。
关于java - PoolingClientConnectionManager 性能问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15761035/