HttpClient高併發記憶體溢位
阿新 • • 發佈:2019-02-14
apache 的HttpClient很強大,據說可以承受一萬左右的高併發,但是在做專案的時候用HttpClient進行附件上傳,併發1000不到的時候都導致了記憶體溢位,核心程式碼為:
HttpPost post = new HttpPost(url.toString()); post.setEntity(multipartEntityBuilder.build());
HttpResponse response = httpClient.execute(post);
經過除錯和檢視httpClient的原始碼發現,由於httpClient.execute(post)返回值response並不能close,因此在上傳大檔案而且高併發的情況下會導致執行緒一直被佔用,導致資源不足
用CloseableHttpClient來替代HttpClient,httpClient.execute(post)得到CloseableHttpResponse可以被關閉,從而避免了上述問題
HttpPost post = new HttpPost(url.toString());
post.setEntity(multipartEntityBuilder.build());
// try with resource語法response.close()會被自動呼叫
try (CloseableHttpResponse response = httpClient.execute(post)) {
} catch (Exception ex) {
} finally {
}