0
我使用很多http連接與Apache HttpClient(org.apache.httpcomponents 4.3.6)來測試服務器,並且我無法強制連接關閉,即使在另一個線程中在10秒鐘後計劃HttpConnectionManager
到httpClient.getConnectionManager().shutdown();
時也是如此。如何強制Apache HttpClient/HttpConnection絕對關閉tcp連接?
httpClient.close()
也沒有幫助。
連接可以持續幾分鐘甚至幾小時。
我已經定製SocketConfig
嘗試,這也沒有幫助:
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(false)
.setSoLinger(5)
.setSoReuseAddress(true)
.setSoTimeout(5000)
.setTcpNoDelay(true).build();
的方式,我取的內容:
HttpUriRequest request = new HttpGet(url);
HttpResponse response = httpClient.execute(request);
try (InputStream in = response.getEntity().getContent()) {
String result = IOUtils.toString(in, StandardCharsets.UTF_8);
httpClient.close();
return result;
}
的方式我建立HTTP客戶端:
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(false)
.setSoLinger(configuration.getInt("proxy.list.socket.so.linger"))
.setSoReuseAddress(true)
.setSoTimeout(configuration.getInt("proxy.list.socket.so.timeout"))
.setTcpNoDelay(true).build();
HttpClientBuilder builder = HttpClientBuilder.create();
builder.disableAutomaticRetries();
builder.disableContentCompression();
builder.disableCookieManagement();
builder.disableRedirectHandling();
builder.setConnectionReuseStrategy(new NoConnectionReuseStrategy());
builder.setDefaultSocketConfig(socketConfig);
我的關機原型之一:
shutdownExecutor.schedule(() -> {
httpClient.getConnectionManager().closeExpiredConnections();
httpClient.getConnectionManager().closeIdleConnections(1, TimeUnit.SECONDS);
httpClient.getConnectionManager().shutdown();
httpClient.notifyAll();
try {
httpClient.close();
} catch (IOException ex) {
}
}, configuration.getInt("proxy.test.forced.timeout.seconds"), TimeUnit.SECONDS);
String content = HttpContentFetcher.getAndCloseClient(url, httpClient);
你可以發佈一個最小樣本?你如何試圖關閉連接,你爲什麼說它沒有效果? – Raffaele
@Raffaele它在閱讀反應上發揮作用。粘貼的細節。其實我很確定我已經達到了暫停,但長度約爲300秒,而不是我想要的10秒。 –
在代碼中使用套接字逗留並期望套接字在同一時間立即關閉是有點奇怪的。 – oleg