Netty学习系列(2)

373 阅读17分钟

四、Netty概述

1. 官网

官网:netty.io/

img

netty版本说明:

  1. Netty 版本分为 Netty 3.xNetty 4.xNetty 5.x
  2. 因为 Netty 5 出现重大 bug,已经被官网废弃了,目前推荐使用的是 Netty 4.x的稳定版本
  3. 目前在官网可下载的版本 Netty 3.xNetty 4.0.xNetty 4.1.x
  4. 本文使用版本:Netty4.1.x
  5. Netty 下载地址:bintray.com/netty/downl…

2. Netty优势

  • Netty产生背景
    1. NIO 的类库和 API 繁杂,使用麻烦:需要熟练掌握 SelectorServerSocketChannelSocketChannelByteBuffer等。
    2. 需要具备其他的额外技能:要熟悉 Java 多线程编程,因为 NIO 编程涉及到 Reactor 模式,你必须对多线程和网络编程非常熟悉,才能编写出高质量的 NIO 程序。
    3. 开发工作量和难度都非常大:例如客户端面临断连重连、网络闪断、半包读写、失败缓存、网络拥塞和异常流的处理等等。
    4. JDK NIOBug:例如臭名昭著的 Epoll Bug,它会导致 Selector 空轮询,最终导致 CPU100%。直到 JDK1.7 版本该问题仍旧存在,没有被根本解决。
  • Netty优点
    1. 设计优雅:适用于各种传输类型的统一 API 阻塞和非阻塞 Socket;基于灵活且可扩展的事件模型,可以清晰地分离关注点;高度可定制的线程模型-单线程,一个或多个线程池。
    2. 使用方便:详细记录的 Javadoc,用户指南和示例;没有其他依赖项,JDK5(Netty3.x)6(Netty4.x)就足够了。
    3. 高性能、吞吐量更高:延迟更低;减少资源消耗;最小化不必要的内存复制。
    4. 安全:完整的 SSL/TLSStartTLS 支持。
    5. 社区活跃、不断更新:社区活跃,版本迭代周期短,发现的 Bug 可以被及时修复,同时,更多的新功能会被加入。

五、Netty架构设计

1. 线程模型基本介绍

  1. 不同的线程模式,对程序的性能有很大影响,目前存在的线程模型有:传统阻塞 I/O 服务模型和 Reactor 模式
  2. 根据 Reactor 的数量和处理资源池线程的数量不同,有 3 种典型的实现
    • Reactor 单线程
    • Reactor多线程
    • 主从 Reactor多线程
  3. Netty 主要基于主从 Reactor 多线程模型做了一定的改进,其中主从 Reactor 多线程模型有多个 Reactor

2. 传统阻塞IO服务模型

image-20210721102017311

阻塞IO模式每个连接都需要独立的线程完成数据的输入、业务处理、数据返回

当并发数很大的时候,就会创建大量的线程,占用大量资源,连接创建后,如果当前线程暂时没有数据可读,该线程就会阻塞在read操作,造成资源浪费

3. Reactor模式

3.1 设计思路

  • 基于IO复用模型:多个连接共用一个阻塞对象,应用程序只需要在一个阻塞对象等待,无需阻塞等待所有连接。当某个连接有新的数据可以处理时,操作系统通知应用程序,线程从阻塞状态返回,开始进行业务处理 Reactor

    对应的模式:

    • 反应器模式
    • 分发者模式(Dispatcher)
    • 通知者模式(Notifier)
  • 基于线程池复用线程资源:不必再为每个连接创建线程,将连接完成后的业务处理任务分配给线程进行处理,一个线程可以处理多个连接的业务。

image-20210721102917689

  1. Reactor 模式,通过一个或多个输入同时传递给服务处理器的模式(基于事件驱动)
  2. 服务器端程序处理传入的多个请求,并将它们同步分派到相应的处理线程,因此 Reactor 模式也叫 Dispatcher 模式
  3. Reactor 模式使用 IO 复用监听事件,收到事件后,分发给某个线程(进程),这点就是网络服务器高并发处理关键

3.2 模式分类

根据 Reactor 的数量和处理资源池线程的数量不同,有 3 种典型的实现

  1. Reactor 单线程
  2. Reactor 多线程
  3. 主从 Reactor 多线程

3.2.1 单 Reactor 单线程

image-20210721104800152

3.2.1.1 方案说明
  1. Select 是前面 I/O 复用模型介绍的标准网络编程 API,可以实现应用程序通过一个阻塞对象监听多路连接请求
  2. Reactor 对象通过 Select 监控客户端请求事件,收到事件后通过 Dispatch 进行分发
  3. 如果是建立连接请求事件,则由 Acceptor 通过 Accept 处理连接请求,然后创建一个 Handler 对象处理连接完成后的后续业务处理
  4. 如果不是建立连接事件,则 Reactor 会分发调用连接对应的 Handler 来响应
  5. Handler 会完成 Read → 业务处理 → Send 的完整业务流程

结合实例:服务器端用一个线程通过多路复用搞定所有的 IO 操作(包括连接,读、写等),编码简单,清晰明了,但是如果客户端连接数量较多,将无法支撑,前面的 NIO群聊系统就属于这种模型

3.2.1.2 优缺点分析
  1. 优点:模型简单,没有多线程、进程通信、竞争的问题,全部都在一个线程中完成
  2. 缺点:性能问题,只有一个线程,无法完全发挥多核 CPU 的性能。Handler在处理某个连接上的业务时,整个进程无法处理其他连接事件,很容易导致性能瓶颈
  3. 缺点:可靠性问题,线程意外终止,或者进入死循环,会导致整个系统通信模块不可用,不能接收和处理外部消息,造成节点故障
  4. 使用场景:客户端的数量有限,业务处理非常快速,比如 Redis 在业务处理的时间复杂度 O(1) 的情况

3.2.2 单 Reactor 多线程

image-20210721105832976

3.2.2.1 方案说明
  1. Reactor 对象通过 Select 监控客户端请求事件,收到事件后,通过 Dispatch 进行分发
  2. 如果建立连接请求,则由 Acceptor 通过 accept 处理连接请求,然后创建一个 Handler 对象处理完成连接后的各种事件
  3. 如果不是连接请求,则由 Reactor 分发调用连接对应的 handler 来处理
  4. handler 只负责响应事件,不做具体的业务处理,通过 read 读取数据后,会分发给后面的 worker 线程池的某个线程处理业务
  5. worker 线程池会分配独立线程完成真正的业务,并将结果返回给 handler
  6. handler 收到响应后,通过 send 将结果返回给 client
3.2.2.2 优缺点分析
  1. 优点:可以充分的利用多核 cpu 的处理能力
  2. 缺点:多线程数据共享和访问比较复杂,Reactor 处理所有的事件的监听和响应,在高并发场景容易出现性能瓶颈。

3.2.3 主从 Reactor 多线程

image-20210721110839456

3.2.3.1 方案说明
  1. Reactor 主线程 MainReactor 对象通过 select 监听连接事件,收到事件后,通过 Acceptor 处理连接事件
  2. Acceptor 处理连接事件后,MainReactor 将连接分配给 SubReactor
  3. SubReactor 将连接加入到连接队列进行监听,并创建 handler 进行各种事件处理
  4. 当有新事件发生时,SubReactor 就会调用对应的 handler 处理
  5. handler 通过 read 读取数据,分发给后面的 worker 线程处理
  6. worker 线程池分配独立的 worker 线程进行业务处理,并返回结果
  7. handler 收到响应的结果后,再通过 send 将结果返回给 client
  8. Reactor 主线程可以对应多个 Reactor 子线程,即 MainRecator 可以关联多个 SubReactor
3.2.3.2 优缺点分析
  1. 优点:父线程与子线程的数据交互简单,职责明确,父线程只需要接收新连接,子线程完成后续的业务处理。
  2. 优点:父线程与子线程的数据交互简单,Reactor 主线程只需要把新连接传给子线程,子线程无需返回数据。
  3. 缺点:编程复杂度较高
  4. 结合实例:这种模型在许多项目中广泛使用,包括 Nginx 主从 Reactor 多进程模型,Memcached 主从多线程,Netty 主从多线程模型的支持

3.3 小结

用生活案例来理解:

去饭店用餐

  • Reactor单线程:前台接待员和服务员是同一人,全程为一个顾客服务
  • Reactor多线程:1个前台接待员在前台为顾客分配服务员,分配完之后这个服务员就一直为一个顾客服务,接待员只负责接待分配
  • 主从Reactor多线程:有一个接待员组长,接待员组长负责为顾客分配接待员,接待员把顾客带到座位上,为顾客分配服务员

Reactor优势:

  1. 响应快,不必为单个同步时间所阻塞,虽然 Reactor 本身依然是同步的
  2. 可以最大程度的避免复杂的多线程及同步问题,并且避免了多线程/进程的切换开销
  3. 扩展性好,可以方便的通过增加 Reactor 实例个数来充分利用 CPU 资源
  4. 复用性好,Reactor 模型本身与具体事件处理逻辑无关,具有很高的复用性

4. Netty模型

image-20210721142417960

4.1 架构图说明

  1. Netty 分配两组线程池: BossGroup 专门负责接收客户端的连接,WorkerGroup 专门负责网络的读写
  2. BossGroupWorkerGroup 类型都是 NioEventLoopGroup(循环事件组,组中含有多个循环事件,每个事件都是NioEventLoop
  3. NioEventLoop 表示一个不断循环的执行处理任务的线程,每个 NioEventLoop 都有一个 Selector,用于监听绑定在其上的 socket 的网络通讯
  4. NioEventLoopGroup 可以有多个线程,即可以含有多个 NioEventLoop
  5. 每个Boss NioEventLoop循环执行的步骤有3步
    • 轮询 accept 事件
    • 处理 accept 事件,与 client 建立连接,生成 NioScocketChannel,并将其注册到某个 Worker NIOEventLoop 上的 Selector
    • 处理任务队列的任务,即 runAllTasks
  6. 每个Worker NioEventLoop循环执行的步骤
    • 轮询 readwrite 事件
    • 处理 I/O 事件,即 readwrite 事件,在对应 NioScocketChannel 处理
    • 处理任务队列的任务,即 runAllTasks
  7. 每个 Worker NioEventLoop 处理业务时,会使用 pipeline(管道),pipeline 中包含了 channel,即通过 pipeline 可以获取到对应通道,管道中维护了很多的处理器

4.2 编码实例(TCP服务)

实例说明:

  1. 使用netty编写一个服务端和客户端
  2. 客户端发消息给服务端,服务端可以回复消息给客户端

测试步骤:

  1. 启动服务端,输出监听端口成功

    image-20210721153201718

  2. 启动客户端,客户端发消息到服务端,服务端会收到消息打印到控制台

    image-20210721153440097

  3. 服务端消息读取完之后发消息给客户端,客户端收到消息打印到控制台

注:服务端自定义handler中,处理客户端数据时,处理流程可能会比较长,这时可以使用任务的方式来异步执行,详见NettyServerTaskHandler

代码如下:

  • pom.xml需要引入netty包

    <dependency>
    	<groupId>io.netty</groupId>
    	<artifactId>netty-all</artifactId>
    	<version>4.1.51.Final</version>
    </dependency>
    
  • 服务端

    package com.nic.netty.simple;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelFutureListener;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelOption;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.util.CharsetUtil;
    
    import java.nio.charset.Charset;
    
    /**
     * Description:
     * netty服务端
     *
     * @author james
     * @date 2021/7/21 14:34
     */
    public class NettyServer
    {
        public static void main(String[] args) {
    
            //创建Bose Group和Worker Group
            // 1. 创建两个线程组bossGroup和workerGroup
            // 2. bossGroup处理连接,workerGroup处理业务
            // 3. 两个group无限循环
            // 4. bossGroup 1个线程,workerGroup 4个线程
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup workerGroup = new NioEventLoopGroup(4);
    
            try {
                //创建服务端启动对象,配置参数
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, workerGroup)//配置两个线程组
                        .channel(NioServerSocketChannel.class)//使用NioSocketChannel作为服务器通道实现
                        .option(ChannelOption.SO_BACKLOG, 128)//设置线程队列得到的连接个数
                        .childOption(ChannelOption.SO_KEEPALIVE, true)//设置保持活动链接状态
                        //                    .handler(null)
                        .childHandler(new ChannelInitializer<SocketChannel>()//创建一个通道初始化对象
                        {
                            //给pipeline设置处理器
                            @Override
                            protected void initChannel(SocketChannel socketChannel) {
                                System.out.println("客户socketChannel hashcode = " + socketChannel.hashCode());
                                //可以使用一个集合管理 SocketChannel,再推送消息时,可以将业务加入到各个channel对应的NIOEventLoop的taskQueue或者scheduleTaskQueue
                                socketChannel.pipeline().addLast(new ChannelInboundHandlerAdapter()
                                {
                                    //重写ChannelInboundHandlerAdapter中的读数据、数据读取完成、异常处理方法。
                                    //这边也可以另外写一个类继承ChannelInboundHandlerAdapter,然后这边addLast添加这个重写的类
    
                                    /**
                                     *
                                     * @param ctx 上下文对象,含有管道pipeline、通道channel、地址
                                     * @param msg 客户端发送的数据
                                     */
                                    @Override
                                    public void channelRead(ChannelHandlerContext ctx, Object msg) {
                                        System.out.println("服务器读取线程 " + Thread.currentThread().getName());
                                        Channel channel = ctx.channel();
                                        System.out.println("server ctx = " + ctx + ", channel = " + channel);
                                        //                                    System.out.println("看看channel 和 pipeline的关系");
                                        //                                    Channel channel = ctx.channel();
                                        //                                    ChannelPipeline pipeline = ctx.pipeline(); //本质是一个双向链接, 出站入站
    
                                        //将 msg 转成一个 ByteBuf
                                        //ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
                                        ByteBuf buf = (ByteBuf) msg;
                                        System.out.println("客户端发送消息是:" + buf.toString(CharsetUtil.UTF_8));
                                        System.out.println("客户端地址:" + channel.remoteAddress());
                                    }
    
                                    @Override
                                    public void channelReadComplete(ChannelHandlerContext ctx) {
                                        //将数据写入缓存并刷新
                                        System.out.println("channelReadComplete");
                                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello,netty客户端", Charset.defaultCharset()));
                                    }
    
                                    @Override
                                    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
                                        //抛异常之后需要关闭
                                        ctx.close();
                                    }
                                });
                            }
                        });
                System.out.println("服务器 is ready...");
    
                //绑定端口并同步,生成channelFuture对象
                ChannelFuture channelFuture = serverBootstrap.bind(7100).sync();
    
                channelFuture.addListener((ChannelFutureListener) cf -> {
                    if (cf.isSuccess()) {
                        System.out.println("监听端口 7100 成功");
                    }
                    else {
                        System.out.println("监听端口 7100 失败");
                    }
                });
                //对关闭通道进行监听
                channelFuture.channel().closeFuture().sync();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                bossGroup.shutdownGracefully();
                workerGroup.shutdownGracefully();
            }
        }
    }
    
  • 服务端自定义handler

    package com.nic.netty.simple;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    import java.nio.charset.Charset;
    
    /**
     * Description:
     * 重写ChannelInboundHandlerAdapter中的读数据、数据读取完成、异常处理方法。
     *
     * @author james
     * @date 2021/7/21 15:41
     */
    public class NettyServerHandler extends ChannelInboundHandlerAdapter
    {
    
        /**
         * @param ctx 上下文对象,含有管道pipeline、通道channel、地址
         * @param msg 客户端发送的数据
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            System.out.println("服务器读取线程 " + Thread.currentThread().getName());
            Channel channel = ctx.channel();
            System.out.println("server ctx = " + ctx + ", channel = " + channel);
            //                                    System.out.println("看看channel 和 pipeline的关系");
            //                                    Channel channel = ctx.channel();
            //                                    ChannelPipeline pipeline = ctx.pipeline(); //本质是一个双向链接, 出站入站
    
            //将 msg 转成一个 ByteBuf
            //ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("客户端发送消息是:" + buf.toString(CharsetUtil.UTF_8));
            System.out.println("客户端地址:" + channel.remoteAddress());
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException {
            //将数据写入缓存并刷新
            System.out.println("channelReadComplete");
            //此时这边有一个耗时任务,如果直接处理,那服务器这边就会阻塞,应使用任务的方式,不阻塞服务器,详见com.nic.netty.simple.NettyServerTaskHandler
    
            //        Thread.sleep(20 * 1000);
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,netty客户端", Charset.defaultCharset()));
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            //抛异常之后需要关闭
            ctx.close();
        }
    }
    
  • 服务端自定义任务handler

    package com.nic.netty.simple;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.Channel;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    import io.netty.util.CharsetUtil;
    
    import java.util.Date;
    import java.util.concurrent.TimeUnit;
    
    /**
     * Description:
     * 重写ChannelInboundHandlerAdapter中的读数据、数据读取完成、异常处理方法。
     *
     * @author james
     * @date 2021/7/21 15:41
     */
    public class NettyServerTaskHandler extends ChannelInboundHandlerAdapter
    {
    
        /**
         * @param ctx 上下文对象,含有管道pipeline、通道channel、地址
         * @param msg 客户端发送的数据
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            System.out.println("服务器读取线程 " + Thread.currentThread().getName());
            Channel channel = ctx.channel();
            System.out.println("server ctx = " + ctx + ", channel = " + channel);
    
            //将 msg 转成一个 ByteBuf
            //ByteBuf 是 Netty 提供的,不是 NIO 的 ByteBuffer.
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("客户端发送消息是:" + buf.toString(CharsetUtil.UTF_8));
            System.out.println("客户端地址:" + channel.remoteAddress());
        }
    
        @Override
        public void channelReadComplete(ChannelHandlerContext ctx) throws InterruptedException {
            //将数据写入缓存并刷新
            System.out.println("channelReadComplete");
    
            //---------------------------------------------------------
            // 解决方案1 用户程序自定义的普通任务
            System.out.println("execute 1");
            ctx.channel().eventLoop().execute(new Runnable()
            {
                @Override
                public void run() {
    
                    try {
                        Thread.sleep(5 * 1000);
                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端2 " + new Date(), CharsetUtil.UTF_8));
                        System.out.println("channel code=" + ctx.channel().hashCode());
                    }
                    catch (Exception ex) {
                        System.out.println("发生异常" + ex.getMessage());
                    }
                }
            });
            System.out.println("execute 2");
            ctx.channel().eventLoop().execute(new Runnable()
            {
                @Override
                public void run() {
    
                    try {
                        Thread.sleep(5 * 1000);
                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端3 " + new Date(), CharsetUtil.UTF_8));
                        System.out.println("channel code=" + ctx.channel().hashCode());
                    }
                    catch (Exception ex) {
                        System.out.println("发生异常" + ex.getMessage());
                    }
                }
            });
            //---------------------------------------------------------
    
            //---------------------------------------------------------
            //解决方案2 : 用户自定义定时任务 -》 该任务是提交到 scheduleTaskQueue中
            System.out.println("schedule 1");
            ctx.channel().eventLoop().schedule(new Runnable()
            {
                @Override
                public void run() {
    
                    try {
                        Thread.sleep(5 * 1000);
                        ctx.writeAndFlush(Unpooled.copiedBuffer("hello, 客户端4 " + new Date(), CharsetUtil.UTF_8));
                        System.out.println("channel code=" + ctx.channel().hashCode());
                    }
                    catch (Exception ex) {
                        System.out.println("发生异常" + ex.getMessage());
                    }
                }
            }, 5, TimeUnit.SECONDS);
            //---------------------------------------------------------
    
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            //抛异常之后需要关闭
            ctx.close();
        }
    }
    
  • 客户端

    package com.nic.netty.simple;
    
    import io.netty.bootstrap.Bootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioSocketChannel;
    
    /**
     * Description:
     * netty服务端
     *
     * @author james
     * @date 2021/7/21 15:01
     */
    public class NettyClient
    {
        public static void main(String[] args) {
            NioEventLoopGroup group = new NioEventLoopGroup();
    
            try {
                Bootstrap bootstrap = new Bootstrap();
                bootstrap.group(group)
                        .channel(NioSocketChannel.class)
                        .handler(new ChannelInitializer<SocketChannel>()
                        {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) {
                                socketChannel.pipeline().addLast(new NettyClientHandler());
                            }
                        });
                System.out.println("客户端 is ok。。。");
                ChannelFuture channelFuture = bootstrap.connect("127.0.0.1", 7100).sync();
                channelFuture.channel().closeFuture().sync();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                group.shutdownGracefully();
            }
        }
    }
    
  • 客户端自定义handler

    package com.nic.netty.simple;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.ChannelInboundHandlerAdapter;
    
    import java.nio.charset.Charset;
    
    /**
     * Description:
     *
     * @author james
     * @date 2021/7/21 15:42
     */
    public class NettyClientHandler extends ChannelInboundHandlerAdapter
    {
        /**
         * 通道就绪就会触发该方法
         *
         * @param ctx
         */
        @Override
        public void channelActive(ChannelHandlerContext ctx) {
            System.out.println("client = " + ctx);
            ctx.writeAndFlush(Unpooled.copiedBuffer("hello,netty服务端", Charset.defaultCharset()));
        }
    
        /**
         * 通道有读取事件时触发
         *
         * @param ctx
         * @param msg
         */
        @Override
        public void channelRead(ChannelHandlerContext ctx, Object msg) {
            System.out.println("channelRead");
            ByteBuf buf = (ByteBuf) msg;
            System.out.println("服务器回复:" + buf.toString(Charset.defaultCharset()));
            System.out.println("服务器地址:" + ctx.channel().remoteAddress());
        }
    
        @Override
        public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) {
            cause.printStackTrace();
            ctx.close();
        }
    }
    

5. 异步模型

5.1 基本介绍

  • Netty中的I/O操作是异步的,包括Bind、Write、Connect 等操作会简单的返回一个 ChannelFuture,调用者并不能立刻获得结果,而是通过 Future-Listener 机制,用户可以方便的主动获取或者通过通知机制获得 IO 操作结果。

  • Netty的异步模型是建立在 futurecallback 的之上的。callback 就是回调。重点说 Future,它的核心思想是:假设一个方法 fun,计算过程可能非常耗时,等待 fun 返回显然不合适。那么可以在调用 fun 的时候,立马返回一个 Future,后续可以通过 Future 去监控方法 fun 的处理过程(即:Future-Listener 机制)

5.2 工作原理

image-20210721160700352

  1. 在使用 Netty 进行编程时,拦截操作和转换出入站数据只需要您提供 callback 或利用 future 即可。这使得链式操作简单、高效,并有利于编写可重用的、通用的代码。
  2. Netty 框架的目标就是让你的业务逻辑从网络基础应用编码中分离出来、解脱出来。

5.3 Future-Listener机制

  1. Future 对象刚刚创建时,处于非完成状态,调用者可以通过返回的 ChannelFuture 来获取操作执行的状态,注册监听函数来执行完成后的操作。

  2. 常见有如下操作

    • 通过 isDone 方法来判断当前操作是否完成;
    • 通过 isSuccess 方法来判断已完成的当前操作是否成功;
    • 通过 getCause 方法来获取已完成的当前操作失败的原因;
    • 通过 isCancelled 方法来判断已完成的当前操作是否被取消;
    • 通过 addListener 方法来注册监听器,当操作已完成(isDone方法返回完成),将会通知指定的监听器;如果 Future 对象已完成,则通知指定的监听器

    如下图:绑定端口是异步操作,当绑定操作处理完,将会调用相应的监听器处理逻辑

    image-20210721160914474

5.4 编码实例(HTTP服务)

实例说明:

  1. 浏览器访问localhost:7101
  2. 服务器收到请求,回复字符串

测试步骤:

  1. 浏览器访问localhost:7101,收到了服务器的回复

    image-20210721165056570

  2. 服务器收到浏览器的请求控制台打印信息

    image-20210721165158576

代码如下:

  • 服务端

    package com.nic.netty.http;
    
    import io.netty.bootstrap.ServerBootstrap;
    import io.netty.channel.ChannelFuture;
    import io.netty.channel.ChannelInitializer;
    import io.netty.channel.ChannelPipeline;
    import io.netty.channel.nio.NioEventLoopGroup;
    import io.netty.channel.socket.SocketChannel;
    import io.netty.channel.socket.nio.NioServerSocketChannel;
    import io.netty.handler.codec.http.HttpServerCodec;
    
    /**
     * Description:
     *
     * @author james
     * @date 2021/7/21 16:11
     */
    public class HttpServer
    {
        public static void main(String[] args) {
            NioEventLoopGroup bossGroup = new NioEventLoopGroup(1);
            NioEventLoopGroup wrokerGroup = new NioEventLoopGroup(4);
    
            try {
                ServerBootstrap serverBootstrap = new ServerBootstrap();
                serverBootstrap.group(bossGroup, wrokerGroup)
                        .channel(NioServerSocketChannel.class)
                        .childHandler(new ChannelInitializer<SocketChannel>()
                        {
                            @Override
                            protected void initChannel(SocketChannel socketChannel) throws Exception {
                                ChannelPipeline pipeline = socketChannel.pipeline();
                                //加入一个netty 提供的httpServerCodec codec =>[coder - decoder]
                                //HttpServerCodec 说明
                                //1. HttpServerCodec 是netty 提供的处理http的 编-解码器
                                pipeline.addLast("MyHttpServerCodec", new HttpServerCodec());
                                pipeline.addLast("MyHttpServerHandler", new HttpServerHandler());
                                System.out.println("服务器 is ready...");
                            }
                        });
                ChannelFuture channelFuture = serverBootstrap.bind(7101).sync();
                channelFuture.channel().closeFuture().sync();
            }
            catch (InterruptedException e) {
                e.printStackTrace();
            }
            finally {
                bossGroup.shutdownGracefully();
                wrokerGroup.shutdownGracefully();
            }
        }
    }
    
  • 服务端自定义handler

    package com.nic.netty.http;
    
    import io.netty.buffer.ByteBuf;
    import io.netty.buffer.Unpooled;
    import io.netty.channel.ChannelHandlerContext;
    import io.netty.channel.SimpleChannelInboundHandler;
    import io.netty.handler.codec.http.DefaultFullHttpResponse;
    import io.netty.handler.codec.http.HttpHeaderNames;
    import io.netty.handler.codec.http.HttpObject;
    import io.netty.handler.codec.http.HttpRequest;
    import io.netty.handler.codec.http.HttpResponseStatus;
    import io.netty.handler.codec.http.HttpVersion;
    import io.netty.util.CharsetUtil;
    
    import java.net.URI;
    
    /**
     * Description:
     * SimpleChannelInboundHandler<I> extends ChannelInboundHandlerAdapter
     * HttpObject 客户端和服务器端相互通讯的数据被封装成 HttpObject
     *
     * @author james
     * @date 2021/7/21 16:14
     */
    public class HttpServerHandler extends SimpleChannelInboundHandler<HttpObject>
    {
    
        @Override
        protected void channelRead0(ChannelHandlerContext ctx, HttpObject httpObject) throws Exception {
            System.out.println("对应的channel=" + ctx.channel() + " pipeline=" + ctx.pipeline() + " 通过pipeline获取channel" + ctx.pipeline().channel());
    
            System.out.println("当前ctx的handler=" + ctx.handler());
    
            if (httpObject instanceof HttpRequest) {
                System.out.println("ctx类型:" + ctx.getClass());
    
                System.out.println("pipeline hashcode = " + ctx.pipeline().hashCode() + " HttpServerHandler hash = " + this.hashCode());
                System.out.println("httpObjec 类型:" + httpObject.getClass());
                System.out.println("客户端地址:" + ctx.channel().remoteAddress());
    
                HttpRequest httpRequest = (HttpRequest) httpObject;
    
                URI uri = new URI(httpRequest.uri());
                if ("/favicon.ico".equals(uri.getPath())) {
                    System.out.println("请求了favicon.ico,不做相应");
                    return;
                }
    
                //回复信息给浏览器
                ByteBuf buf = Unpooled.copiedBuffer("hellolllllllll", CharsetUtil.UTF_8);
                //构建http相应
                DefaultFullHttpResponse response = new DefaultFullHttpResponse(HttpVersion.HTTP_1_1, HttpResponseStatus.OK, buf);
                response.headers().set(HttpHeaderNames.CONTENT_TYPE, "text/plain");
                response.headers().set(HttpHeaderNames.CONTENT_LENGTH, buf.readableBytes());
    
                ctx.writeAndFlush(response);
            }
        }
    }
    

完整代码 https://github.com/beiJxx/netty_test

资料参考

dongzl.github.io/netty-handb…

cloud.tencent.com/developer/a…

www.cnblogs.com/lsgxeva/p/1…