Netty源码解析-服务启动过程


前言

Netty是一个高性能、异步事件驱动的网络应用框架,用于快速开发可维护的高性能协议服务器和客户端。它的服务启动过程涉及多个组件和步骤,下面我将对Netty的服务启动过程进行详细的源码解析。

简单Netty服务器启动代码示例

public class NettyServer {
    public void start() throws Exception {
        // 初始化BossGroup和WorkerGroup线程池
        EventLoopGroup bossGroup = new NioEventLoopGroup();
        EventLoopGroup workerGroup = new NioEventLoopGroup();
        try {
            // 初始化ServerBootstrap
            ServerBootstrap b = new ServerBootstrap();
            b.group(bossGroup, workerGroup)
             .channel(NioServerSocketChannel.class)
             .childHandler(new ChannelInitializer<SocketChannel>() {
                 @Override
                 public void initChannel(SocketChannel ch) throws Exception {
                     // 添加自定义的ChannelHandler处理业务逻辑
                     ch.pipeline().addLast(new MyChannelHandler());
                 }
             })
             .option(ChannelOption.SO_BACKLOG, 128)
             .childOption(ChannelOption.SO_KEEPALIVE, true);
 
            // 绑定端口并启动服务
            ChannelFuture f = b.bind(8080).sync();
 
            // 等待服务关闭
            f.channel().closeFuture().sync();
        } finally {
            // 释放资源
            bossGroup.shutdownGracefully();
            workerGroup.shutdownGracefully();
        }
    }
 
    public static void main(String[] args) throws Exception {
        NettyServer server = new NettyServer();
        server.start();
    }
}
 
class MyChannelHandler extends SimpleChannelInboundHandler<ByteBuf> {
    // 实现相关的事件处理逻辑
    @Override
    protected void channelRead0(ChannelHandlerContext ctx, ByteBuf msg) throws Exception {
        // 处理接收到的数据
    }
}

主线

在这里插入图片描述

main线程:

  • 创建NioEventLoopGroup、创建NioEventLoop
  • 创建 selector
  • 创建 server socket channel
  • 初始化 server socket channel
  • 给 server socket channel 从 boss group 中选择一个 NioEventLoop

boss 线程

  • 将 server socket channel 注册到选择的 NioEventLoop 的 selector
  • 绑定地址启动
  • 注册接受连接事件(OP_ACCEPT)到 selector 上

NioEventLoopGroup初始化

NioEventLoopGroup 初始化的基本过程:

  • EventLoopGroup(其实是MultithreadEventExecutorGroup)内部维护一个类为EventExecutor[] children 数组,其大小是nThreads;
  • 在MultithreadEventExecutorGroup 中会调用newChild()抽象方法来初始化children 数组;
  • 在NioEventLoopGroup 中具体实现newChild()方法,该方法返回一个NioEventLoop 实例。
    初始化NioEventLoop 主要属性:
    provider:在NioEventLoopGroup 构造器中通过SelectorProvider 的provider()方法获取SelectorProvider。
    selector:在NioEventLoop 构造器中调用selector = provider.openSelector()方法获取Selector 对象。

关键代码

 EventLoop eventLoop = EventLoopGroup.newChild(Executor executor, Object... args)  
Selector selector = sun.nio.ch.SelectorProviderImpl.openSelector()
ServerSocketChannel serverSocketChannel = provider.openServerSocketChannel()
selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this);
javaChannel().bind(localAddress, config.getBacklog());
selectionKey.interestOps(OP_ACCEPT);

    private ChannelFuture doBind(final SocketAddress localAddress) {
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.isDone()) {
            // At this point we know that the registration was complete and successful.
            ChannelPromise promise = channel.newPromise();
            doBind0(regFuture, channel, localAddress, promise);
            return promise;
        } else {
            // Registration future is almost always fulfilled already, but just in case it's not.
            final PendingRegistrationPromise promise = new PendingRegistrationPromise(channel);
            regFuture.addListener(new ChannelFutureListener() {
                @Override
                public void operationComplete(ChannelFuture future) throws Exception {
                    Throwable cause = future.cause();
                    if (cause != null) {
                        // Registration on the EventLoop failed so fail the ChannelPromise directly to not cause an
                        // IllegalStateException once we try to access the EventLoop of the Channel.
                        promise.setFailure(cause);
                    } else {
                        // Registration was successful, so set the correct executor to use.
                        // See https://github.com/netty/netty/issues/2586
                        promise.registered();

                        doBind0(regFuture, channel, localAddress, promise);
                    }
                }
            });
            return promise;
        }
    }
    private static void doBind0(
            final ChannelFuture regFuture, final Channel channel,
            final SocketAddress localAddress, final ChannelPromise promise) {

        // 在触发channelRegistered()之前调用此方法。给用户处理程序一个设置的机会
        // the pipeline in its channelRegistered() implementation.
        channel.eventLoop().execute(new Runnable() {
            @Override
            public void run() {
                if (regFuture.isSuccess()) {
                    channel.bind(localAddress, promise).addListener(ChannelFutureListener.CLOSE_ON_FAILURE);
                } else {
                    promise.setFailure(regFuture.cause());
                }
            }
        });
    }
  • Selector 是在 new NioEventLoopGroup()(创建一批 NioEventLoop)时创建。
  • 第一次 Register 并不是监听 OP_ACCEPT,而是 0:
    selectionKey = javaChannel().register(eventLoop().unwrappedSelector(), 0, this) 。
  • 最终监听 OP_ACCEPT 是通过 bind 完成后的 fireChannelActive() 来触发的。
    DefaultChannelPipeline.channelActive->readIfIsAutoRead()->AbstractChannel.read()->DefaultChannelPipeline.read()->AbstractChannelHandlerContext.read() ->AbstractNioChannel.doBeginRead
    AbstractNioChannel类片段
    protected void doBeginRead() throws Exception {
        // Channel.read() or ChannelHandlerContext.read() was called
        final SelectionKey selectionKey = this.selectionKey;
        if (!selectionKey.isValid()) {
            return;
        }
        readPending = true;
        final int interestOps = selectionKey.interestOps();
        if ((interestOps & readInterestOp) == 0) {
            selectionKey.interestOps(interestOps | readInterestOp);
        }
    }

在这里插入图片描述

  • NioEventLoop 是通过 Register 操作的执行来完成启动的。
  • 类似 ChannelInitializer,一些 Hander 可以设计成一次性的,用完就移除,例如授权。
  • 21
    点赞
  • 28
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 10
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 10
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

shandongwill

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值