首页 > 代码库 > netty心跳检测 heartbeat(五)
netty心跳检测 heartbeat(五)
HeartBeat心跳
心跳检测的必要性
1.集群心跳检测,避免网络中断
2.数据同步:主节点写日志,从节点每隔一段时间拉取主节点日志。
心跳检测存在的意义:
客户端和服务端已经建立了长连接,客户端开飞行模式,关机,关闭wifi,服务端不会(感知)收到通知(handRemoved)并关闭连接。
核心事件 :
ChannelInboundHandlerAdapter类的userEventTriggered事件
心跳检测服务端代码 :
server启动类 :
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<SocketChannel> { 2 @Override 3 protected void initChannel(SocketChannel ch) throws Exception { 4 5 ChannelPipeline channelPipeline = ch.pipeline(); 6 7 channelPipeline.addLast(new IdleStateHandler(3,7,10, TimeUnit.SECONDS)); 8 channelPipeline.addLast(new MyHeartBeatHandler()); 9 10 } 11 }
心跳检测逻辑处理handler:
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 }
netty心跳检测 heartbeat(五)
声明:以上内容来自用户投稿及互联网公开渠道收集整理发布,本网站不拥有所有权,未作人工编辑处理,也不承担相关法律责任,若内容有误或涉及侵权可进行投诉: 投诉/举报 工作人员会在5个工作日内联系你,一经查实,本站将立刻删除涉嫌侵权内容。