我一直在尝试使用Apache HTTPClient(v4.1)为我的应用程序实现连接池。问题是,尽管有足够多的线程并行运行,但是客户端在运行时始终仅建立两个连接。我已经尝试修改代码一段时间了,但是还没有任何帮助。
我使用ThreadSafeClientConnManager
连接池,并设置MaxTotal
和DefaulMaxPerRoute
我想要的值。
您首先想到什么我想检查的东西吗?
这是我用来创建客户端的代码段。
DefaultHttpClient createClient() {
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(60000));
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(60000));
params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 6443));
registry.register(new Scheme("http", 80, PlainSocketFactory.getSocketFactory()));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(params, registry);
cm.setMaxTotal(2 * maxConnections);
cm.setDefaultMaxPerRoute(maxConnections);
HttpHost localhost = new HttpHost("localhost");
cm.setMaxForRoute(new HttpRoute(localhost), maxConnections);
HttpHost sdpTargetHost = new HttpHost("webserviceIP", webservicePort, "https");
cm.setMaxForRoute(new HttpRoute(sdpTargetHost, null, true), maxConnections);
return new DefaultHttpClient(cm, params);
}
此函数返回的客户端用于Runnables
托管ThreadPoolExecutor
。Runnables使用客户端,并具有以下几行:
HttpResponse response = httpClient.execute(httpPost, context);
HttpEntity entity = response.getEntity();
....
EntityUtils.consume(entity);
据我所知,EntityUtils.consume(entity)
它将通知连接管理器该连接已不再使用,因此将释放该连接以供其他线程使用。因此,我猜想连接管理还可以。
我想我已经提供了足够的信息,请告诉我是否要添加更多内容。
谢谢
好。我已经找到了解决方案,这要感谢oleg指出了日志记录以及Google和所有论坛。
我要做的就是仅使用连接管理器定义类,然后使用HttpClient.setParams()设置HttpParams。因此,代码将如下所示:
DefaultHttpClient createClient() {
SchemeRegistry registry = new SchemeRegistry();
registry.register(new Scheme("https", sf, 6443));
ThreadSafeClientConnManager cm = new ThreadSafeClientConnManager(registry);
cm.setMaxTotal(maxConnections);
cm.setDefaultMaxPerRoute(maxConnections);
HttpHost targetHost = new HttpHost("webserviceIP", webservicePort, "https");
cm.setMaxForRoute(new HttpRoute(targetHost, null, true), maxConnections);
return new DefaultHttpClient(cm);
}
在使用客户端之前,
DefaultHttpClient httpClient = createClient();
HttpParams params = new BasicHttpParams();
HttpProtocolParams.setVersion(params, HttpVersion.HTTP_1_1);
HttpProtocolParams.setContentCharset(params, HTTP.UTF_8);
params.setIntParameter(CoreConnectionPNames.SO_TIMEOUT, new Integer(60000));
params.setIntParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, new Integer(60000));
params.setBooleanParameter(CoreConnectionPNames.TCP_NODELAY, true);
httpClient.setParams(params);
逻辑上代码显然没有区别,但这解决了我的问题。我认为这可能是HttpClient 4.1 API中的某种bug。
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句