在上一篇文章里我们介绍了 httpclient 连接池中连接的重用,以及连接的 keep alive ,在这里我们主要介绍连接的可用性检查。
连接的可用性检查
对于 httpclient 连接池中的连接是可复用的,但是会存在这种情况,就是当我们从连接池中申请到连接的时候,很有可能连接不可用。比方说远端 server 关闭了连接,这样的话连接就不可用了。httpclient 提供了连接可用性检查机制,主要涉及了以下几个关键点:
何时进行可用性检查
if (config.isStaleConnectionCheckEnabled()) {
// validate connection
if (managedConn.isOpen()) {
this.log.debug("Stale connection check");
if (managedConn.isStale()) {
this.log.debug("Stale connection detected");
managedConn.close();
}
}
}
如何进行可用性检查
public boolean isStale() {
if (!isOpen()) {
return true;
}
try {
final int bytesRead = fillInputBuffer(1);
return bytesRead < 0;
} catch (final SocketTimeoutException ex) {
return false;
} catch (final IOException ex) {
return true;
}
}
private int fillInputBuffer(final int timeout) throws IOException {
final Socket socket = this.socketHolder.get();
final int oldtimeout = socket.getSoTimeout();
try {
socket.setSoTimeout(timeout);
return this.inBuffer.fillBuffer();
} finally {
socket.setSoTimeout(oldtimeout);
}
}
可用性检查之后的处理
if (!managedConn.isOpen()) {
this.log.debug("Opening connection " + route);
try {
establishRoute(proxyAuthState, managedConn, route, request, context);
} catch (final TunnelRefusedException ex) {
if (this.log.isDebugEnabled()) {
this.log.debug(ex.getMessage());
}
response = ex.getResponse();
break;
}
}