再次来到NetworkClient的poll方法,我们会发现这样一个方法
//处理超时的请求
handleTimedOutRequests(responses, updatedNow);
private void handleTimedOutRequests(List<ClientResponse> responses, long now) {
//获取到请求超时的主机
List<String> nodeIds = this.inFlightRequests.getNodesWithTimedOutRequests(now, this.requestTimeoutMs);
for (String nodeId : nodeIds) {
// close connection to the node
//关闭请求超时的主机的连接
this.selector.close(nodeId);
log.debug("Disconnecting from node {} due to request timeout.", nodeId);
//修改连接的状态
processDisconnection(responses, nodeId, now);
}
// we disconnected, so we should probably refresh our metadata
if (nodeIds.size() > 0)
metadataUpdater.requestUpdate();
}
public List<String> getNodesWithTimedOutRequests(long now, int requestTimeout) {
List<String> nodeIds = new LinkedList<>();
for (Map.Entry<String, Deque<ClientRequest>> requestEntry : requests.entrySet()) {
String nodeId = requestEntry.getKey();
Deque<ClientRequest> deque = requestEntry.getValue();
if (!deque.isEmpty()) {
ClientRequest request = deque.peekLast();
long timeSinceSend = now - request.sendTimeMs();
//计算是否超时,如果有主机超时了
if (timeSinceSend > requestTimeout)
//把超时的主机加入到nodeIds里面。
nodeIds.add(nodeId);
}
}
return nodeIds;
}
private void processDisconnection(List<ClientResponse> responses, String nodeId, long now) {
//修改连接状态
connectionStates.disconnected(nodeId, now);
for (ClientRequest request : this.inFlightRequests.clearAll(nodeId)) {
log.trace("Cancelled request {} due to node {} being disconnected", request, nodeId);
if (!metadataUpdater.maybeHandleDisconnection(request))
//对这些请求进行处理
//自己封装了一个响应,这个响应里面没有服务端响应消息(服务端没给响应)
//失去连接的标识为true
responses.add(new ClientResponse(request, now, true, null));
}
}
这里可以看到,如果超时连接会断开,然后重新初始化,尝试建立连接。