美文网首页
Netty服务端启动流程

Netty服务端启动流程

作者: 隔壁王哥 | 来源:发表于2022-05-04 13:43 被阅读0次

概述

Netty底层基于java nio,本章节将通过服务端启动流程,对其进行分析,从中了解Netty原理。

服务端启动代码

EventLoopGroup bossGroup = new NioEventLoopGroup();
EventLoopGroup workerGroup = new NioEventLoopGroup();
ServerBootstrap b = new ServerBootstrap();
b.group(bossGroup, workerGroup)
        .channel(NioServerSocketChannel.class)
        .option(...)
        .childOption(...)
        .attr(...)
        .childAttr(...)
        .handler(new ChannelInitializer<ServerSocketChannel>() {...})
        .childHandler(new ChannelInitializer<SocketChannel>() {...});

ChannelFuture f = b.bind(8888).sync();
f.channel().closeFuture().sync();

Netty服务端通过ServerBootstrap这个引导类进行配置并启动

  • group:通过配置两个线程池组指定其线程模型
  • channel:配置IO模型为NIO
  • option方法:配置TCP底层属性
  • childOption:为新连接配置TCP底层属性
  • attr:为NioServerSocketChannel配置自定义属性
  • childAttr:为新连接配置自定义属性
  • handler:配置新连接建立前的逻辑处理器
  • childHandler:配置新连接建立后的逻辑处理器。
  • bind:绑定端口,启动服务。

服务端启动流程

服务端启动的核心是bind方法,启动过程包括以下几个步骤:

  • 初始化:创建并初始化NioServerSocketChannel
  • 注册:将ServerSocketChannel注册到bossGroup中的某个EventLoop对应的Selector上
  • 绑定:绑定端口,注册OP_ACCEPT事件
ServerBootstrap#bind
  ->AbstractBootstrap#doBind
    ->initAndRegister
        ->ReflectiveChannelFactory#newChannel
        ->ServerBootstrap#init
        ->AbstractUnsafe#register
    ->doBind0
        ->AbstractUnsafe#bind
        ->AbstractNioUnsafe#doBeginRead

创建Selector

在实例化线程池组NioEventLoopGroup时,默认会创建2倍CPU核心数的NioEventLoop,每个NioEventLoop对应一个Java NIO的 Selector对象。

Selector selector = SelectorProvider.openSelector();

创建NioServerSocketChannel

#AbstractBootstrap
private ChannelFuture doBind(final SocketAddress localAddress) {
    final ChannelFuture regFuture = initAndRegister();
    ...
}
final ChannelFuture initAndRegister() {
    Channel channel = channelFactory.newChannel();
    ...
}

在配置引导类的channel属性时,会初始化AbstractBootstrap对象的channelFactory属性,channelFactory类型为ReflectiveChannelFactory<NioServerSocketChannel>,channelFactory#newChannel内部通过反射进行NioServerSocketChannel对象的创建。

NioServerSocketChannel实例化时会创建JDK底层的ServerSocketChannel,同时会调用其父类构造方法设置NioServerSocketChannel为非阻塞模式,并初始化ChannelId、Unsafe、DefaultChannelPipeline这几个属性。

初始化NioServerSocketChannel

#AbstractBootstrap
void init(Channel channel) throws Exception {
    ...
    ChannelPipeline p = channel.pipeline();
    // 配置ChannelPipeline
    p.addLast(new ChannelInitializer<Channel>() {
        @Override
        public void initChannel(Channel ch) throws Exception {
            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(
                            currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                }
            });
        }
    });
}

初始化主要配置 NioServerSocketChannel的TCP底层参数、配置自定义属性、初始化新连接TCP底层配置属性与自定义属性、配置ChannelPipeline。

ChannelInitializer#initChannel方法将在ServerSocketChannel注册到Selector上,触发回调时执行。initChannel方法会将自定义Handler添加到pipline中,同时通过串行无锁化的方式将一个内置的Handler:ServerBootstrapAcceptor添加到pipline中,这个ServerBootstrapAcceptor作用是接收到新连接后,将新连接注册到workGroup中的某个EventLoop对应的Selector上。

注册

#AbstractBootstrap
final ChannelFuture initAndRegister() {
    ...
    ChannelFuture regFuture = config().group().register(channel);
    ...
}

注册分为三步,第一步:绑定NioEventLoop,第二步:将ServerSocketChannel注册到Selector上,第三步:触发事件

AbstractChannel#register0
    ->MultithreadEventLoopGroup#register
      ->SingleThreadEventLoop#register
        ->AbstractUnsafe#register
            ->AbstractUnsafe#register0
                ->AbstractNioChannel#doRegister
                ->DefaultChannelPipeline#invokeHandlerAddedIfNeeded
                ->DefaultChannelPipeline#fireChannelRegistered
  • 绑定NioEventLoop:在实例化NioEventLoopGroup时会初始化一个chooser对象:EventExecutorChooser,该选择器目的就是选择一个NioEventLoop
#MultithreadEventLoopGroup
public ChannelFuture register(Channel channel) {
    return next().register(channel);
}
public EventLoop next() {
    return (EventLoop) super.next();
}
public EventExecutor next() {
    return chooser.next();
}
  • 注册到Selector:将ServerSocketChannel注册到EventLoop对应的Selector上,并且将当前的NioServerSocketChannel作为一个attachment绑定到jdk底层的channel中,方便后续获取
#AbstractNioChannel#AbstractNioUnsafe
protected void doRegister() throws Exception {
    ...
    selectionKey = javaChannel().register(eventLoop().selector, 0, this);
    ...
}
  • 触发事件:触发handlerAdded事件,ChannelInitializer#handlerAdded方法会判断channel是否注册,此时已经注册,会调用initChannel方法添加handler。触发channelRegistered事件,调用DefaultChannelPipeline#fireChannelRegistered方法传播channelRegistered事件。

绑定

绑定最终会调用NioServerSocketChannel#doBind方法,其中javaChannel是初始化ServerBootstrap时创建的ServerSocketChannel。

#NioServerSocketChannel
protected void doBind(SocketAddress localAddress) throws Exception {
    if (PlatformDependent.javaVersion() >= 7) {
        javaChannel().bind(localAddress, config.getBacklog());
    } else {
        javaChannel().socket().bind(localAddress, config.getBacklog());
    }
}

绑定成功后会触发channelActive事件,最终会调用AbstractNioChannel#doBeginRead方法注册OP_ACCEPT事件

#AbstractNioChannel
protected void doBeginRead() throws Exception {
    // Channel.read() or ChannelHandlerContext.read() was called
    final SelectionKey selectionKey = this.selectionKey;
    if (!selectionKey.isValid()) {
        return;
    }

    readPending = true;
    // 注册OP_ACCEPT事件,
    final int interestOps = selectionKey.interestOps();
    if ((interestOps & readInterestOp) == 0) {
        selectionKey.interestOps(interestOps | readInterestOp);
    }
}

相关文章

网友评论

      本文标题:Netty服务端启动流程

      本文链接:https://www.haomeiwen.com/subject/sytmyrtx.html