netty心跳检测 heartbeat(五)
2021-07-03 18:04
标签:bind sys color pre write bootstrap null prot ring 心跳检测的必要性 1.集群心跳检测,避免网络中断 2.数据同步:主节点写日志,从节点每隔一段时间拉取主节点日志。 心跳检测存在的意义: 客户端和服务端已经建立了长连接,客户端开飞行模式,关机,关闭wifi,服务端不会(感知)收到通知(handRemoved)并关闭连接。 核心事件 : ChannelInboundHandlerAdapter类的userEventTriggered事件 心跳检测服务端代码 : server启动类 : 心跳检测初始化类 : 心跳检测逻辑处理handler: netty心跳检测 heartbeat(五) 标签:bind sys color pre write bootstrap null prot ring 原文地址:http://www.cnblogs.com/fubinhnust/p/7123584.htmlHeartBeat心跳
1 public class HeartBeatServer {
2
3 public static void main(String[] args) throws InterruptedException {
4
5 EventLoopGroup bossGroup = new NioEventLoopGroup();
6 EventLoopGroup workerGroup = new NioEventLoopGroup();
7
8 try{
9 ServerBootstrap serverBootstrap = new ServerBootstrap();
10 serverBootstrap.group(bossGroup,workerGroup).
11 channel(NioServerSocketChannel.class)
12 .handler(new LoggingHandler(LogLevel.INFO))
13 .childHandler(new MyHeartBeatInitializer());
14
15 ChannelFuture channelFuture = serverBootstrap.bind(8899).sync();
16 channelFuture.channel().closeFuture().sync();
17 }finally {
18 bossGroup.shutdownGracefully();
19 workerGroup.shutdownGracefully();
20 }
21
22 }
23
24 }
1 public class MyHeartBeatInitializer extends ChannelInitializer
1 public class MyHeartBeatHandler extends ChannelInboundHandlerAdapter {
2
3 @Override
4 public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
5
6 if(evt instanceof IdleStateEvent){
7 IdleStateEvent idleStateEvent = (IdleStateEvent)evt;
8
9 String eventType = null;
10
11 switch (idleStateEvent.state()){
12 case READER_IDLE:
13 eventType = "读空闲";
14 break;
15 case WRITER_IDLE:
16 eventType = "写空闲";
17 break;
18 case ALL_IDLE:
19 eventType = "读写空闲";
20 break;
21
22 }
23
24 System.out.println(ctx.channel().remoteAddress()+" 超时事件:"+eventType);
25
26 ctx.channel().close();
27 }
28
29 }
30 }