TCP建立连接时需要三次握手的交互如下图
sequenceDiagram
Client->>Server: syn
Server->>Client: ack+syn
Client->>Server: ack
在检测TCP端口时可以基于三次握手的原理来快速检测端口是否通讯正常,目前很多负载均衡设备检测端口连通性时采用客户端发送syn包当收到对应的ack+syn后发送rest断开链接,但是这种问题会在Netty应用上产生rest异常。为了避免syn探活检测异常日志的打印我们可以继承ChannelInboundHandlerAdapter来忽略指定的异常来避免rest异常频繁打印的问题。
@Override
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
if (ignoreException(cause)) {
if (logger.isDebugEnabled()) {
logger.debug(
"{} 'connection reset by peer / broken pipe' error that occurred " +
"while writing close_notify in response to the peer's close_notify", ctx.channel(), cause);
}
if (ctx.channel().isActive()) {
ctx.close();
}
} else {
ctx.fireExceptionCaught(cause);
}
}
ignoreException方法为具体判断是否忽略指定异常
private boolean ignoreException(Throwable t) {
if (!(t instanceof SSLException) && t instanceof IOException) {
String message = String.valueOf(t.getMessage()).toLowerCase();
if (IGNORABLE_ERROR_MESSAGE.matcher(message).matches()) {
return true;
}
//其他异常处理
}
}