Netty 之 Netty生产级的心跳和重连机制

分享一下我老师大神的人工智能教程!零基础,通俗易懂!http://blog.csdn.net/jiangjunshow

也欢迎大家转载本篇文章。分享知识,造福人民,实现我们中华民族伟大复兴!

               

sigh,写这篇博客的时候老脸还是红了一下,心里还是有些唏嘘的,应该算是剽窃吧,每个人的代码功力的确是有差距的,好在文章的标题是“一起学”,而不是开涛大神的“跟我学”系列的文章,我们还是多花点时间学习吧,感叹无用~


最近工作比较忙,但闲暇之余还是看了阿里的冯家春(fengjiachun)的github上的开源代码Jupiter,写的RPC框架让我感叹人外有人,废话不多说,下面的代码全部截取自Jupiter,写了一个比较完整的例子,供大家一起学习分享,再次对@Luca抱拳,Jupiter的Github地址:


https://github.com/fengjiachun/Jupiter


今天研究的是,心跳和重连,虽然这次是大神写的代码,但是万变不离其宗,我们先回顾一下Netty应用心跳和重连的整个过程:

1)客户端连接服务端

2)在客户端的的ChannelPipeline中加入一个比较特殊的IdleStateHandler,设置一下客户端的写空闲时间,例如5s

3)当客户端的所有ChannelHandler中4s内没有write事件,则会触发userEventTriggered方法(上文介绍过)

4)我们在客户端的userEventTriggered中对应的触发事件下发送一个心跳包给服务端,检测服务端是否还存活,防止服务端已经宕机,客户端还不知道

5)同样,服务端要对心跳包做出响应,其实给客户端最好的回复就是“不回复”,这样可以服务端的压力,假如有10w个空闲Idle的连接,那么服务端光发送心跳回复,则也是费事的事情,那么怎么才能告诉客户端它还活着呢,其实很简单,因为5s服务端都会收到来自客户端的心跳信息,那么如果10秒内收不到,服务端可以认为客户端挂了,可以close链路

6)加入服务端因为什么因素导致宕机的话,就会关闭所有的链路链接,所以作为客户端要做的事情就是短线重连


以上描述的就是整个心跳和重连的整个过程,虽然很简单,上一篇blog也写了一个Demo,简单地做了一下上述功能


要写工业级的Netty心跳重连的代码,需要解决一下几个问题:

1)ChannelPipeline中的ChannelHandlers的维护,首次连接和重连都需要对ChannelHandlers进行管理

2)重连对象的管理,也就是bootstrap对象的管理

3)重连机制编写


完整的代码:https://github.com/BazingaLyn/netty-study/tree/master/src/main/java/com/lyncc/netty/idle


下面我们就看大神是如何解决这些问题的,首先先定义一个接口ChannelHandlerHolder,用来保管ChannelPipeline中的Handlers的

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.idle;  
  2.   
  3. import io.netty.channel.ChannelHandler;  
  4.   
  5. /** 
  6.  *  
  7.  * 客户端的ChannelHandler集合,由子类实现,这样做的好处: 
  8.  * 继承这个接口的所有子类可以很方便地获取ChannelPipeline中的Handlers 
  9.  * 获取到handlers之后方便ChannelPipeline中的handler的初始化和在重连的时候也能很方便 
  10.  * 地获取所有的handlers 
  11.  */  
  12. public interface ChannelHandlerHolder {  
  13.   
  14.     ChannelHandler[] handlers();  
  15. }  
我们再来编写我们熟悉的服务端的ServerBootstrap的编写:

HeartBeatServer.java

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.idle;  
  2.   
  3. import io.netty.bootstrap.ServerBootstrap;  
  4. import io.netty.channel.ChannelFuture;  
  5. import io.netty.channel.ChannelInitializer;  
  6. import io.netty.channel.ChannelOption;  
  7. import io.netty.channel.EventLoopGroup;  
  8. import io.netty.channel.nio.NioEventLoopGroup;  
  9. import io.netty.channel.socket.SocketChannel;  
  10. import io.netty.channel.socket.nio.NioServerSocketChannel;  
  11. import io.netty.handler.codec.string.StringDecoder;  
  12. import io.netty.handler.codec.string.StringEncoder;  
  13. import io.netty.handler.logging.LogLevel;  
  14. import io.netty.handler.logging.LoggingHandler;  
  15. import io.netty.handler.timeout.IdleStateHandler;  
  16.   
  17. import java.net.InetSocketAddress;  
  18. import java.util.concurrent.TimeUnit;  
  19.   
  20. public class HeartBeatServer {  
  21.       
  22.     private final AcceptorIdleStateTrigger idleStateTrigger = new AcceptorIdleStateTrigger();  
  23.       
  24.     private int port;  
  25.   
  26.     public HeartBeatServer(int port) {  
  27.         this.port = port;  
  28.     }  
  29.   
  30.     public void start() {  
  31.         EventLoopGroup bossGroup = new NioEventLoopGroup(1);  
  32.         EventLoopGroup workerGroup = new NioEventLoopGroup();  
  33.         try {  
  34.             ServerBootstrap sbs = new ServerBootstrap().group(bossGroup, workerGroup)  
  35.                     .channel(NioServerSocketChannel.class).handler(new LoggingHandler(LogLevel.INFO))  
  36.                     .localAddress(new InetSocketAddress(port)).childHandler(new ChannelInitializer<SocketChannel>() {  
  37.                         protected void initChannel(SocketChannel ch) throws Exception {  
  38.                             ch.pipeline().addLast(new IdleStateHandler(500, TimeUnit.SECONDS));  
  39.                             ch.pipeline().addLast(idleStateTrigger);  
  40.                             ch.pipeline().addLast("decoder"new StringDecoder());  
  41.                             ch.pipeline().addLast("encoder"new StringEncoder());  
  42.                             ch.pipeline().addLast(new HeartBeatServerHandler());  
  43.                         };  
  44.   
  45.                     }).option(ChannelOption.SO_BACKLOG, 128).childOption(ChannelOption.SO_KEEPALIVE, true);  
  46.             // 绑定端口,开始接收进来的连接  
  47.             ChannelFuture future = sbs.bind(port).sync();  
  48.   
  49.             System.out.println("Server start listen at " + port);  
  50.             future.channel().closeFuture().sync();  
  51.         } catch (Exception e) {  
  52.             bossGroup.shutdownGracefully();  
  53.             workerGroup.shutdownGracefully();  
  54.         }  
  55.     }  
  56.   
  57.     public static void main(String[] args) throws Exception {  
  58.         int port;  
  59.         if (args.length > 0) {  
  60.             port = Integer.parseInt(args[0]);  
  61.         } else {  
  62.             port = 8080;  
  63.         }  
  64.         new HeartBeatServer(port).start();  
  65.     }  
  66.   
  67. }  
单独写一个AcceptorIdleStateTrigger,其实也是继承ChannelInboundHandlerAdapter,重写userEventTriggered方法,因为客户端是write,那么服务端自然是read,设置的状态就是IdleState.READER_IDLE,源码如下:

[java]  view plain  copy
  在CODE上查看代码片 派生到我的代码片
  1. package com.lyncc.netty.idle;  
  2.   
  3. import io.netty.channel.ChannelHandler;  
  4. import io.netty.channel.ChannelHandlerContext;  
  5. import io.netty.channel.ChannelInboundHandlerAdapter;  
  6. import io.netty.handler.timeout.IdleState;  
  7. import io.netty.handler.timeout.IdleStateEvent;  
  8.   
  9.   
  10. @ChannelHandler.Sharable  
  11. public class AcceptorIdleStateTrigger extends ChannelInboundHandlerAdapter {  
  12.   
  13.     @Override  
  14.     public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {  
  15.         if (evt instanceof IdleStateEvent) {  
  16.             IdleState state = ((IdleStateEvent) evt).state();  
  17.             if (state == IdleState.READER_IDLE) {  
  18.                 throw new Exception("idle exception");  

猜你喜欢

转载自blog.csdn.net/hgffhh/article/details/83988282