Netty编解码
    Netty涉及到编解码的组件有Channel、ChannelHandler、ChannelPipe等,先大概了解下这几个组件的作用。
    ChannelHandler
    ChannelHandler充当了处理入站和出站数据的应用程序逻辑容器。例如,实现ChannelInboundHandler接口(或ChannelInboundHandlerAdapter),你就可以接收入站事件和数据,这些数据随后会被你的应用程序的业务逻辑处理。当你要给连接的客户端发送响应时,也可以从ChannelInboundHandler冲刷数据。你的业务逻辑通常写在一个或者多个ChannelInboundHandler中。ChannelOutboundHandler原理一样,只不过它是用来处理出站数据的。
    ChannelPipeline
    ChannelPipeline提供了ChannelHandler链的容器。以客户端应用程序为例,如果事件的运动方向是从客户端到服务端的,那么我们称这些事件为出站的,即客户端发送给服务端的数据会通过pipeline中的一系列ChannelOutboundHandler(ChannelOutboundHandler调用是从tail到head方向逐个调用每个handler的逻辑),并被这些Handler处理,反之则称为入站的,入站只调用pipeline里的ChannelInboundHandler逻辑(ChannelInboundHandler调用是从head到tail方向逐个调用每个handler的逻辑)
    image.png
    编码解码器
    当你通过Netty发送或者接受一个消息的时候,就将会发生一次数据转换。入站消息会被解码:从字节转换为另一种格式(比如java对象);如果是出站消息,它会被编码成字节
    Netty提供了一系列实用的编码解码器,他们都实现了ChannelInboundHadnler或者ChannelOutboundHandler接口。在这些类中,channelRead方法已经被重写了。以入站为例,对于每个从入站Channel读取的消息,这个方法会被调用。随后,它将调用由已知解码器所提供的decode()方法进行解码,并将已经解码的字节转发给ChannelPipeline中的下一个ChannelInboundHandler。
    Netty提供了很多编解码器,比如编解码字符串的StringEncoder和StringDecoder,编解码对象的ObjectEncoder和ObjectDecoder等。
    如果要实现高效的编解码可以用protobuf,但是protobuf需要维护大量的proto文件比较麻烦,现在一般可以使用protostuff。
    protostuff是一个基于protobuf实现的序列化方法,它较于protobuf最明显的好处是,在几乎不损耗性能的情况下做到了不用我们写.proto文件来实现序列化。使用它也非常简单,代码如下:
    引入依赖:

    1. <dependency>
    2. <groupId>com.dyuproject.protostuff</groupId>
    3. <artifactId>protostuff-api</artifactId>
    4. <version>1.0.10</version>
    5. </dependency>
    6. <dependency>
    7. <groupId>com.dyuproject.protostuff</groupId>
    8. <artifactId>protostuff-core</artifactId>
    9. <version>1.0.10</version>
    10. </dependency>
    11. <dependency>
    12. <groupId>com.dyuproject.protostuff</groupId>
    13. <artifactId>protostuff-runtime</artifactId>
    14. <version>1.0.10</version>
    15. </dependency>

    protostuff使用示例:

    1. import com.dyuproject.protostuff.LinkedBuffer;
    2. import com.dyuproject.protostuff.ProtostuffIOUtil;
    3. import com.dyuproject.protostuff.Schema;
    4. import com.dyuproject.protostuff.runtime.RuntimeSchema;
    5. import java.util.Map;
    6. import java.util.concurrent.ConcurrentHashMap;
    7. /**
    8. * protostuff 序列化工具类,基于protobuf封装
    9. */
    10. public class ProtostuffUtil {
    11. private static Map<Class<?>, Schema<?>> cachedSchema = new ConcurrentHashMap<Class<?>, Schema<?>>();
    12. private static <T> Schema<T> getSchema(Class<T> clazz) {
    13. @SuppressWarnings("unchecked")
    14. Schema<T> schema = (Schema<T>) cachedSchema.get(clazz);
    15. if (schema == null) {
    16. schema = RuntimeSchema.getSchema(clazz);
    17. if (schema != null) {
    18. cachedSchema.put(clazz, schema);
    19. }
    20. }
    21. return schema;
    22. }
    23. /**
    24. * 序列化
    25. *
    26. * @param obj
    27. * @return
    28. */
    29. public static <T> byte[] serializer(T obj) {
    30. @SuppressWarnings("unchecked")
    31. Class<T> clazz = (Class<T>) obj.getClass();
    32. LinkedBuffer buffer = LinkedBuffer.allocate(LinkedBuffer.DEFAULT_BUFFER_SIZE);
    33. try {
    34. Schema<T> schema = getSchema(clazz);
    35. return ProtostuffIOUtil.toByteArray(obj, schema, buffer);
    36. } catch (Exception e) {
    37. throw new IllegalStateException(e.getMessage(), e);
    38. } finally {
    39. buffer.clear();
    40. }
    41. }
    42. /**
    43. * 反序列化
    44. *
    45. * @param data
    46. * @param clazz
    47. * @return
    48. */
    49. public static <T> T deserializer(byte[] data, Class<T> clazz) {
    50. try {
    51. T obj = clazz.newInstance();
    52. Schema<T> schema = getSchema(clazz);
    53. ProtostuffIOUtil.mergeFrom(data, obj, schema);
    54. return obj;
    55. } catch (Exception e) {
    56. throw new IllegalStateException(e.getMessage(), e);
    57. }
    58. }
    59. public static void main(String[] args) {
    60. byte[] userBytes = ProtostuffUtil.serializer(new User(1, "zhuge"));
    61. User user = ProtostuffUtil.deserializer(userBytes, User.class);
    62. System.out.println(user);
    63. }
    64. }

    参见项目示例com.tuling.netty.codec包下代码
    Netty粘包拆包
    TCP是一个流协议,就是没有界限的一长串二进制数据。TCP作为传输层协议并不不了解上层业务数据的具体含义,它会根据TCP缓冲区的实际情况进行数据包的划分,所以在业务上认为是一个完整的包,可能会被TCP拆分成多个包进行发送,也有可能把多个小的包封装成一个大的数据包发送,这就是所谓的TCP粘包和拆包问题。面向流的通信是无消息保护边界的。
    如下图所示,client发了两个数据包D1和D2,但是server端可能会收到如下几种情况的数据。
    image.png
    解决方案
    1)消息定长度,传输的数据大小固定长度,例如每段的长度固定为100字节,如果不够空位补空格
    2)在数据包尾部添加特殊分隔符,比如下划线,中划线等,这种方法简单易行,但选择分隔符的时候一定要注意每条数据的内部一定不能出现分隔符。
    3)发送长度:发送每条数据的时候,将数据的长度一并发送,比如可以选择每条数据的前4位是数据的长度,应用层处理时可以根据长度来判断每条数据的开始和结束。
    Netty提供了多个解码器,可以进行分包的操作,如下:

    • LineBasedFrameDecoder (回车换行分包)
    • DelimiterBasedFrameDecoder(特殊分隔符分包)
    • FixedLengthFrameDecoder(固定长度报文来分包)

    自定义长度分包编解码器,参见项目示例com.tuling.netty.split包下代码
    Netty心跳检测机制
    所谓心跳, 即在 TCP 长连接中, 客户端和服务器之间定期发送的一种特殊的数据包, 通知对方自己还在线, 以确保 TCP 连接的有效性.
    在 Netty 中, 实现心跳机制的关键是 IdleStateHandler, 看下它的构造器:

    1. public IdleStateHandler(int readerIdleTimeSeconds, int writerIdleTimeSeconds, int allIdleTimeSeconds) {
    2. this((long)readerIdleTimeSeconds, (long)writerIdleTimeSeconds, (long)allIdleTimeSeconds, TimeUnit.SECONDS);
    3. }

    这里解释下三个参数的含义:

    • readerIdleTimeSeconds: 读超时. 即当在指定的时间间隔内没有从 Channel 读取到数据时, 会触发一个 READER_IDLE 的 IdleStateEvent 事件.
    • writerIdleTimeSeconds: 写超时. 即当在指定的时间间隔内没有数据写入到 Channel 时, 会触发一个 WRITER_IDLE 的 IdleStateEvent 事件.
    • allIdleTimeSeconds: 读/写超时. 即当在指定的时间间隔内没有读或写操作时, 会触发一个 ALL_IDLE 的 IdleStateEvent 事件.

    注:这三个参数默认的时间单位是秒。若需要指定其他时间单位,可以使用另一个构造方法:

    1. IdleStateHandler(boolean observeOutput, long readerIdleTime, long writerIdleTime, long allIdleTime, TimeUnit unit)

    要实现Netty服务端心跳检测机制需要在服务器端的ChannelInitializer中加入如下的代码:

    1. pipeline.addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));

    初步地看下IdleStateHandler源码,先看下IdleStateHandler中的channelRead方法:
    image.png
    红框代码其实表示该方法只是进行了透传,不做任何业务逻辑处理,让channelPipe中的下一个handler处理channelRead方法
    我们再看看channelActive方法:
    image.png
    这里有个initialize的方法,这是IdleStateHandler的精髓,接着探究:
    image.png
    这边会触发一个Task,ReaderIdleTimeoutTask,这个task里的run方法源码是这样的:
    image.png
    第一个红框代码是用当前时间减去最后一次channelRead方法调用的时间,假如这个结果是6s,说明最后一次调用channelRead已经是6s之前的事情了,你设置的是5s,那么nextDelay则为-1,说明超时了,那么第二个红框代码则会触发下一个handler的userEventTriggered方法:
    image.png
    如果没有超时则不触发userEventTriggered方法。
    Netty心跳检测代码示例:

    1. //服务端代码
    2. public class HeartBeatServer {
    3. public static void main(String[] args) throws Exception {
    4. EventLoopGroup boss = new NioEventLoopGroup();
    5. EventLoopGroup worker = new NioEventLoopGroup();
    6. try {
    7. ServerBootstrap bootstrap = new ServerBootstrap();
    8. bootstrap.group(boss, worker)
    9. .channel(NioServerSocketChannel.class)
    10. .childHandler(new ChannelInitializer<SocketChannel>() {
    11. @Override
    12. protected void initChannel(SocketChannel ch) throws Exception {
    13. ChannelPipeline pipeline = ch.pipeline();
    14. pipeline.addLast("decoder", new StringDecoder());
    15. pipeline.addLast("encoder", new StringEncoder());
    16. //IdleStateHandler的readerIdleTime参数指定超过3秒还没收到客户端的连接,
    17. //会触发IdleStateEvent事件并且交给下一个handler处理,下一个handler必须
    18. //实现userEventTriggered方法处理对应事件
    19. pipeline.addLast(new IdleStateHandler(3, 0, 0, TimeUnit.SECONDS));
    20. pipeline.addLast(new HeartBeatHandler());
    21. }
    22. });
    23. System.out.println("netty server start。。");
    24. ChannelFuture future = bootstrap.bind(9000).sync();
    25. future.channel().closeFuture().sync();
    26. } catch (Exception e) {
    27. e.printStackTrace();
    28. } finally {
    29. worker.shutdownGracefully();
    30. boss.shutdownGracefully();
    31. }
    32. }
    33. }
    1. //服务端处理handler
    2. public class HeartBeatServerHandler extends SimpleChannelInboundHandler<String> {
    3. int readIdleTimes = 0;
    4. @Override
    5. protected void channelRead0(ChannelHandlerContext ctx, String s) throws Exception {
    6. System.out.println(" ====== > [server] message received : " + s);
    7. if ("Heartbeat Packet".equals(s)) {
    8. ctx.channel().writeAndFlush("ok");
    9. } else {
    10. System.out.println(" 其他信息处理 ... ");
    11. }
    12. }
    13. @Override
    14. public void userEventTriggered(ChannelHandlerContext ctx, Object evt) throws Exception {
    15. IdleStateEvent event = (IdleStateEvent) evt;
    16. String eventType = null;
    17. switch (event.state()) {
    18. case READER_IDLE:
    19. eventType = "读空闲";
    20. readIdleTimes++; // 读空闲的计数加1
    21. break;
    22. case WRITER_IDLE:
    23. eventType = "写空闲";
    24. // 不处理
    25. break;
    26. case ALL_IDLE:
    27. eventType = "读写空闲";
    28. // 不处理
    29. break;
    30. }
    31. System.out.println(ctx.channel().remoteAddress() + "超时事件:" + eventType);
    32. if (readIdleTimes > 3) {
    33. System.out.println(" [server]读空闲超过3次,关闭连接,释放更多资源");
    34. ctx.channel().writeAndFlush("idle close");
    35. ctx.channel().close();
    36. }
    37. }
    38. @Override
    39. public void channelActive(ChannelHandlerContext ctx) throws Exception {
    40. System.err.println("=== " + ctx.channel().remoteAddress() + " is active ===");
    41. }
    42. }
    //客户端代码
       public class HeartBeatClient {
        public static void main(String[] args) throws Exception {
            EventLoopGroup eventLoopGroup = new NioEventLoopGroup();
            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(eventLoopGroup).channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>() {
                            @Override
                            protected void initChannel(SocketChannel ch) throws Exception {
                                ChannelPipeline pipeline = ch.pipeline();
                                pipeline.addLast("decoder", new StringDecoder());
                                pipeline.addLast("encoder", new StringEncoder());
                                pipeline.addLast(new HeartBeatClientHandler());
                            }
                        });
    
                System.out.println("netty client start。。");
                Channel channel = bootstrap.connect("127.0.0.1", 9000).sync().channel();
                String text = "Heartbeat Packet";
                Random random = new Random();
                while (channel.isActive()) {
                    int num = random.nextInt(10);
                    Thread.sleep(num * 1000);
                    channel.writeAndFlush(text);
                }
            } catch (Exception e) {
                e.printStackTrace();
            } finally {
                eventLoopGroup.shutdownGracefully();
            }
        }
    
        static class HeartBeatClientHandler extends SimpleChannelInboundHandler<String> {
    
            @Override
            protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
                System.out.println(" client received :" + msg);
                if (msg != null && msg.equals("idle close")) {
                    System.out.println(" 服务端关闭连接,客户端也关闭");
                    ctx.channel().closeFuture();
                }
            }
        }
    }
    

    Netty断线自动重连实现
    1、客户端启动连接服务端时,如果网络或服务端有问题,客户端连接失败,可以重连,重连的逻辑加在客户端。
    参见代码:

    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.EventLoopGroup;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    import java.util.concurrent.TimeUnit;
    
    /**
     * 实现了重连的客户端
     */
    public class NettyClient {
    
        private String host;
        private int port;
        private Bootstrap bootstrap;
        private EventLoopGroup group;
    
        public static void main(String[] args) throws Exception {
            NettyClient nettyClient = new NettyClient("localhost", 9000);
            nettyClient.connect();
        }
    
        public NettyClient(String host, int port) {
            this.host = host;
            this.port = port;
            init();
        }
    
        private void init() {
            //客户端需要一个事件循环组
            group = new NioEventLoopGroup();
            //创建客户端启动对象
            // bootstrap 可重用, 只需在NettyClient实例化的时候初始化即可.
            bootstrap = new Bootstrap();
            bootstrap.group(group)
                    .channel(NioSocketChannel.class)
                    .handler(new ChannelInitializer<SocketChannel>() {
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            //加入处理器
                            ch.pipeline().addLast(new NettyClientHandler(NettyClient.this));
                        }
                    });
        }
    
        public void connect() throws Exception {
            System.out.println("netty client start。。");
            //启动客户端去连接服务器端
            ChannelFuture cf = bootstrap.connect(host, port);
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (!future.isSuccess()) {
                        //重连交给后端线程执行
                        future.channel().eventLoop().schedule(() -> {
                            System.err.println("重连服务端...");
                            try {
                                connect();
                            } catch (Exception e) {
                                e.printStackTrace();
                            }
                        }, 3000, TimeUnit.MILLISECONDS);
                    } else {
                        System.out.println("服务端连接成功...");
                    }
                }
            });
            //对通道关闭进行监听
            cf.channel().closeFuture().sync();
        }
    }
    

    2、系统运行过程中网络故障或服务端故障,导致客户端与服务端断开连接了也需要重连,可以在客户端处理数据的Handler的channelInactive方法中进行重连。
    参见代码:

    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    public class NettyClientHandler extends ChannelInboundHandlerAdapter {
    
        private NettyClient nettyClient;
    
        public NettyClientHandler(NettyClient nettyClient) {
            this.nettyClient = nettyClient;
        }
    
        /**
         * 当客户端连接服务器完成就会触发该方法
         *
         * @param ctx
         * @throws Exception
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) throws Exception {
            ByteBuf buf = Unpooled.copiedBuffer("HelloServer".getBytes(CharsetUtil.UTF_8));
            ctx.writeAndFlush(buf);
        }
    
        //当通道有读取事件时会触发,即服务端发送数据给客户端
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("收到服务端的消息:" + buf.toString(CharsetUtil.UTF_8));
            System.out.println("服务端的地址: " + ctx.channel().remoteAddress());
        }
    
        // channel 处于不活动状态时调用
        @Override
        public void channelInactive(ChannelHandlerContext ctx) throws Exception {
            System.err.println("运行中断开重连。。。");
            nettyClient.connect();
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
            cause.printStackTrace();
            ctx.close();
        }
    }