二、Netty服务端/客户端启动整体流程

一、综述

Netty 的整体流程相对来说还是比较复杂的,初学者往往会被绕晕。所以这里总结了一下整体的流程,从而对 Netty 的整体服务流程有一个大致的了解。从功能上,流程可以分为服务启动、建立连接、读取数据、业务处理、发送数据、关闭连接以及关闭服务。整体流程如下所示(图中没有包含关闭的部分):
在这里插入图片描述
在这里插入图片描述

在这里插入图片描述

  • Server端工作原理
    在这里插入图片描述
  1. server端启动时绑定本地某个端口,将自己NioServerSocketChannel注册到某个boss NioEventLoop的selector上。
  2. server端包含1个boss NioEventLoopGroup和1个worker NioEventLoopGroup,NioEventLoopGroup相当于1个事件循环组,这个组里包含多个事件循环NioEventLoop,每个NioEventLoop包含1个selector和1个事件循环线程。

每个boss NioEventLoop循环执行的任务包含3步:

  • 第1步:轮询accept事件;
  • 第2步:处理io任务,即accept事件,与client建立连接,生成NioSocketChannel,并将NioSocketChannel注册到某个worker NioEventLoop的selector上;
  • 第3步:处理任务队列中的任务,runAllTasks。任务队列中的任务包括用户调用eventloop.execute或schedule执行的任务,或者其它线程提交到该eventloop的任务。

每个worker NioEventLoop循环执行的任务包含3步:

  • 第1步:轮询read、write事件;
  • 第2步:处理io任务,即read、write事件,在NioSocketChannel可读、可写事件发生时进行处理;
  • 第3步:处理任务队列中的任务,runAllTasks。
  • Client端工作原理
    在这里插入图片描述

client端启动时connect到server,建立NioSocketChannel,并注册到某个NioEventLoop的selector上。client端只包含1个NioEventLoopGroup,每个NioEventLoop循环执行的任务包含3步:

  • 第1步:轮询connect、read、write事件;
  • 第2步:处理io任务,即connect、read、write事件,在NioSocketChannel连接建立、可读、可写事件发生时进行处理;
  • 第3步:处理非io任务,runAllTasks。

二、启动流程概述

  • Netty服务端的启动流程如下:
    在这里插入图片描述
    启动流程大致分为五步
  1. 创建ServerBootstrap实例,ServerBootstrap是Netty服务端的启动辅助类,其存在意义在于其整合了Netty可以提供的所有能力,并且尽可能的进行了封装,以方便我们使用
  2. 设置并绑定EventLoopGroup,EventLoopGroup其实是一个包含了多个EventLoop的NIO线程池,在上一篇文章我们也有比较详细的介绍过EventLoop事件循环机制,不过值得一提的是,Netty中的EventLoop不仅仅只处理IO读写事件,还会处理用户自定义或系统的Task任务
  3. 创建服务端ChannelNioServerSocketChannel,并绑定至一个EventLoop上。在初始化NioServerSocketChannel的同时,会创建ChannelPipeline,ChannelPipeline其实是一个绑定了多个ChannelHandler的执行链,后面我们会详细介绍
  4. 为服务端Channel添加并绑定ChannelHandler,ChannelHandler是Netty开放给我们的一个非常重要的接口,在触发网络读写事件后,Netty都会调用对应的ChannelHandler来处理,后面我们会详细介绍
  5. 为服务端Channel绑定监听端口,完成绑定之后,Reactor线程(也就是第三步绑定的EventLoop线程)就开始执行Selector轮询网络IO事件了,如果Selector轮询到网络IO事件了,则会调用Channel对应的ChannelPipeline来依次执行对应的ChannelHandler
  • netty客户端启动流程
    在这里插入图片描述
  • 关键步骤:
  1. 用户线程创建Bootstrap实例,通过API设置创建客户端相关的参数,异步发起客户端连接
  2. 创建处理客户端连接、I/O读写的Reator线程组NioEventLoopGroup。可以通过构造函数指定I/O线程的个数,默认为CPU内核数的2倍。
  3. 通过Bootstrap的ChannelFactory和用户指定的Channel类型创建用于客户端连接的NioSocketChannel,它的功能类似于JDK NIO类库提供的SocketChannel。
  4. 创建默认的Channel Handler Pipeline,用于调度和执行网络事件。
  5. 异步发起TCP连接,判断连接是否成功。如果成功,则直接将NioSocketChannel注册到多路复用器上,监听读操作位,用于数据报读取和消息发送。如果没有立即连接成功,则注册连接监听位到多路复用器,等待连接结果。
  6. 注册对应的网络监听状态位到多路复用器。
  7. 由多路复用器在I/O现场中轮询Channel,处理连接结果。
  8. 如果连接成功,设置Future结果,发送连接成功事件,触发ChannelPipeline执行。
  9. 有ChannelPipeline调度执行系统和用户的ChannelHandler,执行业务逻辑。
  • 结合代码解析:
    在这里插入图片描述

三、NettyServer启动源码

public class NettyServer {
    public static void main(String[] args) throws Exception {
        //创建BossGroup 和 WorkerGroup
        //说明
        //1. 创建两个线程组 bossGroup 和 workerGroup
        //2. bossGroup 只是处理连接请求 , 真正的和客户端业务处理,会交给 workerGroup完成
        //3. 两个都是无限循环
        //4. bossGroup 和 workerGroup 含有的子线程(NioEventLoop)的个数
        //   默认实际 cpu核数 * 2
        EventLoopGroup bossGroup = new NioEventLoopGroup(1);
        EventLoopGroup workerGroup = new NioEventLoopGroup(); //8
        try {
            //创建服务器端的启动对象,配置参数
            ServerBootstrap bootstrap = new ServerBootstrap();
            //使用链式编程来进行设置
            bootstrap.group(bossGroup, workerGroup) //设置两个线程组
                    .channel(NioServerSocketChannel.class) //使用NioSocketChannel 作为服务器的通道实现
                    .option(ChannelOption.SO_BACKLOG, 128) // 设置线程队列得到连接个数
                    .childOption(ChannelOption.SO_KEEPALIVE, true) //设置保持活动连接状态
//                    .handler(null) // 该 handler对应 bossGroup , childHandler 对应 workerGroup
                    .childHandler(new ChannelInitializer<SocketChannel>() {//创建一个通道初始化对象(匿名对象)
                        //给pipeline 设置处理器
                        @Override
                        protected void initChannel(SocketChannel ch) throws Exception {
                            System.out.println("客户socketchannel hashcode=" + ch.hashCode()); //可以使用一个集合管理 SocketChannel, 再推送消息时,可以将业务加入到各个channel 对应的 NIOEventLoop 的 taskQueue 或者 scheduleTaskQueue
                            ch.pipeline().addLast(new NettyServerHandler());
                        }
                    }); // 给我们的workerGroup 的 EventLoop 对应的管道设置处理器
            System.out.println(".....服务器 is ready...");
            //绑定一个端口并且同步, 生成了一个 ChannelFuture 对象
            //启动服务器(并绑定端口)
            ChannelFuture cf = bootstrap.bind(6668).sync();
            //给cf 注册监听器,监控我们关心的事件
            cf.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    if (cf.isSuccess()) {
                        System.out.println("监听端口 6668 成功");
                    } else {
                        System.out.println("监听端口 6668 失败");
                    }
                }
            });
            //对关闭通道进行监听
            cf.channel().closeFuture().sync();
        }finally {
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
}
  • 简要流程图
    在这里插入图片描述
  • boosGroup和workerGroup内部结构图

在这里插入图片描述

  • 源码解析:
  1. 可以看到上面的代码首先创建了两个EventLoopGroup,Netty的线程模型有三种,而不同的EventLoopGroup配置对应了三种不同的线程模型。这里创建的两个EventLoopGroup则是用了多线程Reactor模型,其中bossEventLoopGroup对应的就是处理Accept事件的线程组,而workEventLoopGroup则负责处理IO读写事件。
  2. 然后就是创建了一个启动辅助类ServerBootstrap,并且配置了如下几个重要参数
  • group : 两个Reactor线程组(bossEventLoopGroup, workEventLoopGroup)
  • channel: 服务端Channel
  • option: 服务端socket参数配置 例如SO_BACKLOG指定内核未连接的Socket连接排队个数
  • handler 服务端Channel对应的Handler
  • childHandler 客户端请求Channel对应的Handler
  1. 绑定服务端监听端口,启动服务 -> ChannelFuture f = b.bind(PORT).sync();
    这篇文章主要是分析Netty的启动流程。我们直接看b.bind(PORT).sync()的源码。bind 发现该方法内部实际调用的doBind(final SocketAddress localAddress)方法
  • bind方法
private ChannelFuture doBind(final SocketAddress localAddress) {
// 初始化服务端Channel
    final ChannelFuture regFuture = initAndRegister();
    final Channel channel = regFuture.channel();
    if (regFuture.cause() != null) {
        return regFuture;
    }
    if (regFuture.isDone()) {
    // 初始化一个 promise(异步回调)
        ChannelPromise promise = channel.newPromise();
        // 绑定监听端口
        doBind0(regFuture, channel, localAddress, promise);
        return promise;
    } 
    .... // 省略其他代码
}

doBind主要做了两个事情

  • initAndRegister() 初始化Channel
  • doBind0 绑定监听端口
final ChannelFuture initAndRegister() {
    Channel channel = null;
    try {
    // new一个新的服务端Channel
        channel = channelFactory.newChannel();
        // 初始化Channel
        init(channel);
    } catch (Throwable t) {
        ...
    }
    // 将Channel注册到EventLoopGroup中一个EventLoop上
    ChannelFuture regFuture = config().group().register(channel);
    if (regFuture.cause() != null) {
        if (channel.isRegistered()) {
            channel.close();
        } else {
            channel.unsafe().closeForcibly();
        }
    }
    return regFuture;
}
  1. channelFactory.newChannel()其实就是通过反射创建配置的服务端Channel类,在这里是NioServerSocketChannel

  2. 创建完成的NioServerSocketChannel进行一些初始化操作,例如将我们配置的Handler加到服务端Channel的pipeline中

  3. 将Channel注册到EventLoopGroup中一个EventLoop上

下面我们来看下NioServerSocketChannel类的构造方法,看看它到底初始化了哪些东西,先看下其继承结构

  • NioServerSocketChannel初始化
    image

下面是它的构造方法的调用顺序,依次分为了四步

// 1
public NioServerSocketChannel() {
// 通过 SelectProvider来初始化一个Java NioServerChannel
    this(newSocket(DEFAULT_SELECTOR_PROVIDER));
}

// 2.
public NioServerSocketChannel(ServerSocketChannel channel) {
    super(null, channel, SelectionKey.OP_ACCEPT);
    // 创建一个配置类,持有Java Channel
    config = new NioServerSocketChannelConfig(this, javaChannel().socket());
}

// 3.
protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
    super(parent);
    this.ch = ch;
    this.readInterestOp = readInterestOp;
    try {
    // 设置Channel为非阻塞
        ch.configureBlocking(false);
    } catch (IOException e) {
        try {
            ch.close();
        } catch (IOException e2) {
            logger.warn(
                        "Failed to close a partially initialized socket.", e2);
        }

        throw new ChannelException("Failed to enter non-blocking mode.", e);
    }
}

// 4
protected AbstractChannel(Channel parent) {
    this.parent = parent;
    // 生成一个channel Id
    id = newId();
    // 创建一个 unSafe 类,unsafe封装了Netty底层的IO读写操作
    unsafe = newUnsafe();
    // 创建一个 pipeline类
    pipeline = newChannelPipeline();
}

可以看到NioServerSocketChannel的构造函数主要是初始化并绑定了以下3类

  1. 绑定一个Java ServerSocketChannel
  2. 绑定一个unsafe类,unsafe封装了Netty底层的IO读写操作
  3. 绑定一个pipeline,每个Channel都会唯一绑定一个pipeline

init(Channel channel)

void init(Channel channel) {
// 设置Socket参数
    setChannelOptions(channel, newOptionsArray(), logger);
    setAttributes(channel, attrs0().entrySet().toArray(EMPTY_ATTRIBUTE_ARRAY));

    ChannelPipeline p = channel.pipeline();
    // 子EventLoopGroup用于完成Nio读写操作
    final EventLoopGroup currentChildGroup = childGroup;
    // 为workEventLoop配置的自定义Handler
    final ChannelHandler currentChildHandler = childHandler;
    final Entry<ChannelOption<?>, Object>[] currentChildOptions;
    synchronized (childOptions) {
        currentChildOptions = childOptions.entrySet().toArray(EMPTY_OPTION_ARRAY);
    }
    // 设置附加参数
    final Entry<AttributeKey<?>, Object>[] currentChildAttrs = childAttrs.entrySet().toArray(EMPTY_ATTRIBUTE_ARRAY);
      // 为服务端Channel pipeline 配置 对应的Handler
    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(final Channel ch) {
            final ChannelPipeline pipeline = ch.pipeline();
            ChannelHandler handler = config.handler();
            if (handler != null) {
                pipeline.addLast(handler);
            }
            ch.eventLoop().execute(new Runnable() {
                @Override
                public void run() {
                    pipeline.addLast(new ServerBootstrapAcceptor(
                            ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}

这里主要是为服务端Channel配置一些参数,以及对应的处理器ChannelHandler,注意这里不仅仅会把我们自定义配置的ChannelHandler加上去,同时还会自动帮我们加入一个系统Handler(ServerBootstrapAcceptor),这就是Netty用来接收客户端请求的Handler,在ServerBootstrapAcceptor内部会完成SocketChannel的连接,EventLoop的绑定等操作,之后我们会着重分析这个类

Channel的注册

// MultithreadEventLoopGroup
public ChannelFuture register(Channel channel) {
// next()会选择一个EventLoop来完成Channel的注册
    return next().register(channel);
}

// SingleThreadEventLoop
public ChannelFuture register(Channel channel) {
    return register(new DefaultChannelPromise(channel, this));
}
// AbstractChannel
public final void register(EventLoop eventLoop, final ChannelPromise promise) {
    ObjectUtil.checkNotNull(eventLoop, "eventLoop");
    if (isRegistered()) {
        promise.setFailure(new IllegalStateException("registered to an event loop already"));
        return;
    }
    if (!isCompatible(eventLoop)) {
        promise.setFailure(
                new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
        return;
    }

    AbstractChannel.this.eventLoop = eventLoop;

    if (eventLoop.inEventLoop()) {
    // 注册逻辑
        register0(promise);
    } 
    ....
}

完成注册流程

  1. 完成实际的Java ServerSocketChannel与Select选择器的绑定
  2. 并触发channelRegistered以及channelActive事件

到这里为止,其实Netty服务端已经基本启动完成了,就差绑定一个监听端口了。可能读者会很诧异,怎么没有看到Nio线程轮询 IO事件的循环呢,讲道理肯定应该有一个死循环才对?那我们下面就把这段代码找出来

在之前的代码中,我们经常会看到这样一段代码

// 往EventLoop中丢了一个异步任务(其实是同步的,因为只有一个Nio线程,不过因为是事件循环机制(丢到一个任务队列中),看起来像是异步的)
eventLoop.execute(new Runnable() {
    @Override
    public void run() {
        ...
    }
});

eventLoop.execute到底做了什么事情?

private void execute(Runnable task, boolean immediate) {
    boolean inEventLoop = inEventLoop();
    // 把当前任务添加到任务队列中
    addTask(task);
    // 不是Nio线程自己调用的话,则表明是初次启动
    if (!inEventLoop) {
    // 启动EventLoop的Nio线程
        startThread();
        ...
    }
    ...
}

/**
 * 启动EventLoop的Nio线程
 */
private void doStartThread() {
    assert thread == null;
    // 启动Nio线程
    executor.execute(new Runnable() {
        @Override
        public void run() {
            thread = Thread.currentThread();
            if (interrupted) {
                thread.interrupt();
            }
            boolean success = false;
            updateLastExecutionTime();
            try {
                SingleThreadEventExecutor.this.run();
                success = true;
            } catch (Throwable t) {
                logger.warn("Unexpected exception from an event executor: ", t);
            } finally {
            ... 
}

通过上面的代码可以知道这里主要做了两件事情

  1. 创建的任务被丢入了一个队列中等待执行
  2. 如果是初次创建,则启动Nio线程
  3. SingleThreadEventExecutor.this.run(); 调用子类的Run实现(执行IO事件的轮询) 看下
    NioEventLoop的Run方法实现
protected void run() {
    int selectCnt = 0;
    for (;;) {
        try {
            int strategy;
            try {
            // 获取IO事件类型
                strategy = selectStrategy.calculateStrategy(selectNowSupplier, hasTasks());
                ... 
                default:
                }
            } catch (IOException e) {
                // 出现异常 重建Selector
                rebuildSelector0();
                selectCnt = 0;
                handleLoopException(e);
                continue;
            }
            selectCnt++;
            cancelledKeys = 0;
            needsToSelectAgain = false;
            final int ioRatio = this.ioRatio;
            boolean ranTasks;
            if (ioRatio == 100) {
                try {
                    if (strategy > 0) {
                    // 处理对应事件,激活对应的ChannelHandler事件
                        processSelectedKeys();
                    }
                } finally {
                    // 处理完事件了才执行全部Task
                    ranTasks = runAllTasks();
                }
            }
            ...
        }   
    }
}

到这里的代码是不是就非常熟悉了,熟悉的死循环轮询事件

  1. 通过Selector来轮询IO事件
  2. 触发Channel所绑定的Handler处理对应的事件
  3. 处理完IO事件了会执行系统或用户自定义加入的Task
  • doBind0
    实际的Bind逻辑在 NioServerSocketChannel中执行,我们直接省略前面一些冗长的调用,来看下最底层的调用代码,发现其实就是调用其绑定的Java Channel来执行对应的监听端口绑定逻辑
protected void doBind(SocketAddress localAddress) throws Exception {
// 如果JDK版本大于7
    if (PlatformDependent.javaVersion() >= 7) {
        javaChannel().bind(localAddress, config.getBacklog());
    } else {
        javaChannel().socket().bind(localAddress, config.getBacklog());
    }
}

四、Netty服务端详细的工作流程图

流程图

参考文章1
参考文章2
参考文章3

  • 0
    点赞
  • 16
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值