HTTP1.1的链接,默认是长链接,不会主动关闭。
LINUX会默认保留链接5天再关闭。
建立HTTP链接其实也是调用TCL的协议去建立,包括开始的时候有三次握手,关闭的时候有四次握手。关闭链接双方都可以发起。
但这些链接可能会被防火墙关掉而不通知建立链接的双方,因此设置需设置链接的存活期。
使用httpClient的链接池时,要设置池中的链接存活期或设置存活策略。
检测存活期只在每次发送数据时,才检测取出的链接是否超过存活期,如超过则关闭。
设置存活期的策略:
import java.util.concurrent.TimeUnit;
import org.apache.http.HeaderElement;
import org.apache.http.HeaderElementIterator;
import org.apache.http.HttpResponse;
import org.apache.http.conn.ConnectionKeepAliveStrategy;
import org.apache.http.message.BasicHeaderElementIterator;
import org.apache.http.protocol.HTTP;
import org.apache.http.protocol.HttpContext;
import org.apache.http.util.Args;
public class MyConnectionKeepAliveStrategy implements ConnectionKeepAliveStrategy{
private int timeToLive;
private TimeUnit timeUnit;
public MyConnectionKeepAliveStrategy(int timeToLive, TimeUnit timeUnit) {
this.timeToLive = timeToLive;
this.timeUnit = timeUnit;
}
@Override
public long getKeepAliveDuration(final HttpResponse response, final HttpContext context) {
Args.notNull(response, "HTTP response");
final HeaderElementIterator it = new BasicHeaderElementIterator(
response.headerIterator(HTTP.CONN_KEEP_ALIVE));
while (it.hasNext()) {
final HeaderElement he = it.nextElement();
final String param = he.getName();
final String value = he.getValue();
if (value != null && param.equalsIgnoreCase("timeout")) {
try {
return Long.parseLong(value) * 1000;
} catch(final NumberFormatException ignore) {
//do nothing
}
}
}
return timeUnit.toMillis(timeToLive);
}
}
《HttpClient官方文档》2.6 连接维持存活策略
http://ifeve.com/httpclient-2-6/httpclient连接池管理,你用对了?
http://ifeve.com/http-connection-pool/HttpClient连接池的一些思考
https://zhuanlan.zhihu.com/p/85524697HTTP协议的Keep-Alive 模式
https://www.jianshu.com/p/49551bda6619