[英]How to completely release connection when using HttpClient?
我使用HttpClient( https://hc.apache.org/httpcomponents-client-4.5.x/index.html )進行許多並行的HTTP調用。 運行一段時間后,它得到以下異常:
java.net.BindException: Address already in use: connect
我試圖關閉所有可見的內容,但是我仍然必須錯過一些東西,因為它仍然存在該錯誤。
如何正確釋放連接以避免此連接泄漏問題?
這是重現此問題的測試用例,在Windows的Java8中運行:
public void test(String url) throws Exception {
List<Thread> threads = new ArrayList<Thread>();
for(int t=0; t<40; t++) {
int tt = t;
threads.add(new Thread(() -> {
for(int i=0; i<Integer.MAX_VALUE; i++) {
URI metadataUri;
try {
metadataUri = new URI(url);
} catch (Exception e1) {
e1.printStackTrace();
continue;
}
HttpPost httpRequest = new HttpPost(metadataUri);
httpRequest.setEntity(new ByteArrayEntity( "abc".getBytes()));
//httpRequest.addHeader("Connection", "close");
CloseableHttpClient httpclient = HttpClients.custom().build();
try {
CloseableHttpResponse metadataResponse2 = httpclient.execute(httpRequest);
metadataResponse2.close();
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
httpRequest.completed();
httpRequest.releaseConnection();
} catch (Exception e) {
e.printStackTrace();
}
try {
httpclient.close();
} catch (Exception e) {
e.printStackTrace();
}
}
System.out.println("thread " + tt + " round " + i);
}
}));
}
for(Thread thread : threads) {
thread.start();
}
}
通常,嘗試使用resource( 請參閱參考資料 )應該可以解決此問題:
try (CloseableHttpClient httpclient = HttpClients.custom().build();
CloseableHttpResponse metadataResponse2 = httpclient.execute(httpRequest)) {
} catch (ClientProtocolException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
} finally {
httpRequest.completed();
httpRequest.releaseConnection();
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.