这个问题让我们整个团队都被卡住了半天!
我们使用Apache HttpClient 4.3.x从一个提供HTTP API的存储服务器上获取和提交数据。为了提高性能,我们使用了PoolingHttpClientConnectionManager:
然后获得:
请注意这一行:
我们使用Apache HttpClient 4.3.x从一个提供HTTP API的存储服务器上获取和提交数据。为了提高性能,我们使用了PoolingHttpClientConnectionManager:
public HttpClient createHttpClient() {
Registry registry = RegistryBuilder.create()....build();
PoolingHttpClientConnectionManager connectionManager = new PoolingHttpClientConnectionManager(registry);
connectionManager.setMaxTotal(50);
connectionManager.setDefaultMaxPerRoute(50);
CloseableHttpClient httpClient = HttpClients.custom()
.setConnectionManager(connectionManager)
.build();
return httpClient;
}
接下来我们在程序中使用httpClient实例,每次http请求都重复使用它:
全局httpClient:
HttpClient httpClient = createHttpClient();
提交一些数据:
HttpPost httpPut = new HttpPost("...");
HttpResponse response = httpClient.execute(httpPut);
// Notice we get the response content here!
String content = EntityUtils.toString(response.getEntity());
System.out.println(content);
httpPut.releaseConnection();
response.close();
然后获得:
HttpGet httpGet = new HttpGet("...");
// Blocked at this line !!!!
HttpResponse response = httpClient.execute(httpGet);
String content = EntityUtils.toString(response.getEntity());
System.out.println(content);
httpPut.releaseConnection();
response.close();
请注意这一行:
// Blocked at this line !!!!
程序在那一行被阻塞,无法执行下一行。在调试模式下,我可以看到它被阻塞在:SocketInputStream.socketRead0()
我搜索了很多问题和文档,但都没有获得成功。
我的同事只需设置NoConnectionReuseStrategy.INSTANCE
就解决了问题:
HttpClients.custom()
.setConnectionManager(connectionManager)
// Following line fixed the problem, but why?
.setConnectionReuseStrategy(NoConnectionReuseStrategy.INSTANCE)
.build();
现在它没有被阻止,但为什么呢?
“重用连接”是什么意思?使用NoConnectionReuseStrategy
是否存在性能问题?
谢谢大家~