由于netty采用了事件机制,因此给链路监测和连接管理带来了一些麻烦,因此最好给链路加上心跳处理
(1) 服务器端关键点,主要在initpipe中和实现IdleStateAwareChannelHandler.
pipeline.addLast("timeout", new IdleStateHandler(timer, 10, 10, 0));//此两项为添加心跳机制 10秒查看一次在线的客户端channel是否空闲,IdleStateHandler为netty jar包中提供的类
pipeline.addLast("hearbeat", new Heartbeat());
如果要捕获检测结果,需要继承IdleStateAwareChannelHandler,来判断客户端是否存在,但是这种机制还得一个心跳包发送来检测。
public class Heartbeat extends IdleStateAwareChannelHandler{
int i = 0;
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e)
throws Exception {
// TODO Auto-generated method stub
super.channelIdle(ctx, e);
if(e.getState() == IdleState.WRITER_IDLE)
i++;
if(i==3){
e.getChannel().close();
System.out.println("掉了。");
}
}
}
(2)客户端关键点,也在booststrap,initpipe和IdleStateAwareChannelHandler
bootstrap.setOption("allIdleTime","5"); //这里,很重要
pipeline.addLast("timeout", new IdleStateHandler(timer, 0, 0, 10));
pipeline.addLast("idleHandler", new ClientIdleHandler());

实现IdleStateAwareChannelHandler 的handler负责定时发送检测包
public class ClientIdleHandler extends IdleStateAwareChannelHandler {
final Logger logger = LoggerFactory.getLogger(ClientIdleHandler.class);
@Override
public void channelIdle(ChannelHandlerContext ctx, IdleStateEvent e) throws Exception {
if( e.getState() == IdleState.ALL_IDLE){
logger.debug("链路空闲!发送心跳!S:{} - C:{} idleState:{}", new Object[]{ctx.getChannel().getRemoteAddress(), ctx.getChannel().getLocalAddress() , e.getState()});
e.getChannel().write(MessageHelper.buildMessageEcho());
super.channelIdle(ctx, e);
}
}
}
此外为了获得一些业务阻塞异常导致一些网路不确认状态,采取办法是:用发送upstream的异常来通知解决。
public void exceptionCaught(
ChannelHandlerContext ctx, ExceptionEvent e) throws Exception {
if (this == ctx.getPipeline().getLast()) {
logger.warn(
"EXCEPTION, please implement " + getClass().getName() +
".exceptionCaught() for proper handling.", e.getCause());
}
ctx.sendUpstream(e);
}