如何解决如何使用 PoolingHttpClientConnectionManager 设置连接超时?
由于我计划将 httpclient 依赖项从 v.3.1 升级到 v.4.5.13,但后来我意识到,很多功能都发生了变化,其中之一是,MultiThreadedhttpconnectionManager已从最新版本中删除。 当我在寻找等效的类时,stackoverflow HttpClient 4 - What happened to MultiThreadedHttpConnectionManager? 中的一篇文章建议使用 PoolingHttpClientConnectionManager 类。 但是,我想设置连接超时和套接字超时,这些功能不是由 PoolingHttpClientConnectionManager 提供的。
lines = sum(1 for line in open('data.csv'))
for row in islice(reader,lines)
谁能建议,如何在最近的 httpclient v.4.5.x 中设置连接超时和套接字超时?
解决方法
这是我的代码:
private static class HttpPool {
private static CloseableHttpClient httpClient;
private static final int TIME_OUT = 30;
private static PoolingHttpClientConnectionManager cm;
public static void init() {
cm = new PoolingHttpClientConnectionManager();
cm.setDefaultMaxPerRoute(200);
cm.setMaxTotal(100);
cm.setDefaultMaxPerRoute(20);
HttpHost localhost = new HttpHost("locahost",80);
cm.setMaxPerRoute(new HttpRoute(localhost),50);
ConnectionKeepAliveStrategy kaStrategy = new DefaultConnectionKeepAliveStrategy() {
@Override
public long getKeepAliveDuration(HttpResponse response,HttpContext context) {
long keepAlive = super.getKeepAliveDuration(response,context);
if (keepAlive == -1) {
keepAlive = 0;
}
return keepAlive;
}
};
SocketConfig socketConfig = SocketConfig.custom()
.setSoKeepAlive(false)
.setSoLinger(1)
.setSoReuseAddress(true)
.setSoTimeout(TIME_OUT)
.setTcpNoDelay(true).build();
RequestConfig config = RequestConfig.custom()
.setConnectTimeout(TIME_OUT)
.setConnectionRequestTimeout(TIME_OUT)
.setSocketTimeout(TIME_OUT).build();
httpClient = HttpClients.custom()
.setConnectionManager(cm)
.setKeepAliveStrategy(kaStrategy)
.setDefaultRequestConfig(config)
.setDefaultSocketConfig(socketConfig)
.setRetryHandler((IOException exception,int executionCount,HttpContext context) -> false)
.build();
new Thread(() -> new Timer().schedule(new TimerTask() {
@Override
public void run() {
// Close expired connections
cm.closeExpiredConnections();
// Optionally,close connections
// that have been idle longer than 30 sec
cm.closeIdleConnections(30,TimeUnit.SECONDS);
}
},5000)).start();
}
public static CloseableHttpClient getClient() {
if (httpClient == null) {
synchronized (HttpPool.class) {
if (httpClient == null) {
init();
}
}
}
return httpClient;
}
}
部分代码抄袭,如有错误请指出
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。