对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上

写在前面

建议没有看我之前文章的同学可以看我之前的系列文章,方便后续的理解。

对话写 Netty 代码的同学,你真的懂 Netty 了吗?(二)之主线流程

这里我们稍微回顾一下,上篇文章介绍了 NettyServer 服务端的前两步即:

第一部分 new NioEventLoopGroup(nThreads)
第二部分 初始化赋值逻辑 new ServerBootstrap() 的链式赋值操作

NioEventLoopGroup 包含的核心属性
taskQueue 、Selector、Executor
对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第1张图片

ServerBootstrap 的核心属性

EventLoopGroup ServerBootstrap.childGroup (workerGroup 事件接收处理)
EventLoopGroup AbstractBootstrap.group (bossGroup 事件创建)
ChannelFactory AbstractBootstrap.channelFactory (channel
反射工厂,最后用于实例化 C) Map, Object>
AbstractBootstrap.options (Bootstrap 的配置项) ChannelHandler
ServerBootstrap.childHandler (通道处理器,初始化我们自定义的处理器链路)

本篇将深入最后一步 bootstrap.bind(inetPort).sync(); 探索 Netty 最深层的奥秘

第三部 bootstrap.bind(inetPort).sync();

首先我们进入 bind(int inetPort) 方法:


    /**
     * Create a new {@link Channel} and bind it.
     */
    public ChannelFuture bind(int inetPort) {
     
        return bind(new InetSocketAddress(inetPort));
    }
    public ChannelFuture bind(SocketAddress localAddress) {
     
        validate();
        if (localAddress == null) {
     
            throw new NullPointerException("localAddress");
        }
        return doBind(localAddress);
    }

最终调用链路到主干代码 doBind 方法中

    private ChannelFuture doBind(final SocketAddress localAddress) {
     
        final ChannelFuture regFuture = initAndRegister();
        final Channel channel = regFuture.channel();
        if (regFuture.cause() != null) {
     
            return regFuture;
        }

        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 {
     
                        // Registrati

 1. List item

on 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;
        }
    }

核心方法 doBind

doBind 方法中我们主要关注其中的两个核心方法

  1. initAndRegister();
  2. doBind0()

对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第2张图片

一、initAndRegister() 初始化并注册

这两个方法我们一个一个来跟,首先是 initAndRegister

final ChannelFuture initAndRegister() {
     
        Channel channel = null;
        try {
     
            channel = channelFactory.newChannel();
            init(channel);
        } catch (Throwable t) {
     
            if (channel != null) {
     
                // channel can be null if newChannel crashed (eg SocketException("too many open files"))
                channel.unsafe().closeForcibly();
                // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
                return new DefaultChannelPromise(channel, GlobalEventExecutor.INSTANCE).setFailure(t);
            }
            // as the Channel is not registered yet we need to force the usage of the GlobalEventExecutor
            return new DefaultChannelPromise(new FailedChannel(), GlobalEventExecutor.INSTANCE).setFailure(t);
        }

        ChannelFuture regFuture = config().group().register(channel);
        if (regFuture.cause() != null) {
     
            if (channel.isRegistered()) {
     
                channel.close();
            } else {
     
                channel.unsafe().closeForcibly();
            }
        }
        return regFuture;
    }

抛去异常处理的逻辑我们直接看主干,最核心的我们只需要关心其中的 3 行代码

channel = channelFactory.newChannel();
init(channel);
ChannelFuture regFuture = config().group().register(channel);

1. Channel channel = channelFactory.newChannel();

这行代码熟悉吗,在我们初始化 ServerBootstrap 赋值的时候初始化了 ReflectiveChannelFactory

.channel(NioServerSocketChannel.class)

这里的 channelFactory.newChannel() 操作即相当于调用了 NioServerSocketChannel 的无参构造方法

public class ReflectiveChannelFactory<T extends Channel> implements ChannelFactory<T> {
     

    @Override
    public T newChannel() {
     
        try {
     
            return constructor.newInstance();
        } catch (Throwable t) {
     
            throw new ChannelException("Unable to create Channel from class " + constructor.getDeclaringClass(), t);
        }
    }

这个无参构造方法会有一个很长的 super 调用链路,在深入此链路之前,我们先来看看 newSocket(DEFAULT_SELECTOR_PROVIDER)

    public NioServerSocketChannel() {
     
        this(newSocket(DEFAULT_SELECTOR_PROVIDER));
    }
 private static ServerSocketChannel newSocket(SelectorProvider provider) {
     
        try {
     
            return provider.openServerSocketChannel();
        } catch (IOException e) {
     
            throw new ChannelException(
                    "Failed to open a server socket.", e);
        }
    }

这里就是对 Nio 代码的封装,等同于 ServerSocketChannel.open() 返回了一个 ServerSocketChannel
感兴趣的同学可以回顾一下这篇文章
BIO、NIO 入门(Netty 先导)

所以说 Netty 是对 Nio 的进一步封装。

回到 NioServerSocketChannel 的初始化
看一下继承关系
对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第3张图片
构造方法走过了以下抽象父类,最终完成初始化
对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第4张图片

    public NioServerSocketChannel(ServerSocketChannel channel) {
     
        super(null, channel, SelectionKey.OP_ACCEPT);
        config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }
    protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
     
        super(parent, ch, readInterestOp);
    }
    protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
     
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
     
            ch.configureBlocking(false);
        } catch (IOException e) {
     
            try {
     
                ch.close();
            } catch (IOException e2) {
     
                if (logger.isWarnEnabled()) {
     
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

            throw new ChannelException("Failed to enter non-blocking mode.", e);
        }
    }
    protected AbstractChannel(Channel parent) {
     
        this.parent = parent;
        id = newId();
        unsafe = newUnsafe();
        pipeline = newChannelPipeline();
    }

这里我们按代码执行顺序从下往上看首先 protected AbstractChannel(Channel parent)

unsafe = newUnsafe();

这里 newUnsafe() 通过断点可以看到调用的是 AbstractNioMessageChannel 的方法

AbstractNioMessageChannel
    @Override
    protected AbstractNioUnsafe newUnsafe() {
     
        return new NioMessageUnsafe();
    }

初始化 pipline pipeline = newChannelPipeline();

public abstract class AbstractChannel extends DefaultAttributeMap implements Channel {
     
    protected DefaultChannelPipeline newChannelPipeline() {
     
        return new DefaultChannelPipeline(this);
    }

这里 DefaultChannelPipeline 构建了链表形式的 pipline 并初始化了 tail 和 head

    protected DefaultChannelPipeline(Channel channel) {
     
        this.channel = ObjectUtil.checkNotNull(channel, "channel");
        succeededFuture = new SucceededChannelFuture(channel, null);
        voidPromise =  new VoidChannelPromise(channel, true);

        tail = new TailContext(this);
        head = new HeadContext(this);

        head.next = tail;
        tail.prev = head;
    }

对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第5张图片
最后我们在整体看一下后面的初始化流程

  public NioServerSocketChannel(ServerSocketChannel channel) {
     
        super(null, channel, SelectionKey.OP_ACCEPT);
        config = new NioServerSocketChannelConfig(this, javaChannel().socket());
    }
    protected AbstractNioMessageChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
     
        super(parent, ch, readInterestOp);
    }
    protected AbstractNioChannel(Channel parent, SelectableChannel ch, int readInterestOp) {
     
        super(parent);
        this.ch = ch;
        this.readInterestOp = readInterestOp;
        try {
     
            ch.configureBlocking(false);
        } catch (IOException e) {
     
            try {
     
                ch.close();
            } catch (IOException e2) {
     
                if (logger.isWarnEnabled()) {
     
                    logger.warn(
                            "Failed to close a partially initialized socket.", e2);
                }
            }

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

这里首先将 SelectionKey.OP_ACCEPT 和之前 newSocket(DEFAULT_SELECTOR_PROVIDER) -> provider.openServerSocketChannel() 创建的 ServerSocketChannel 赋值给了 AbstractNioChannel 的成员变量,以及配置非阻塞 ch.configureBlocking(false);

AbstractNioChannel
     this.ch = ch;
     this.readInterestOp = readInterestOp;
     ch.configureBlocking(false);

2. init(channel);

注意一下,init 方法传入的 channel 是 channelFactory.newChannel(); 初始化出来的 NioServerSocketChannel

      channel = channelFactory.newChannel();
      init(channel);

第二部分 init(channel); 是服务端的,所以很明显我们要看的是 ServerBootstrap

在这里插入图片描述
init 方法如下

 @Override
    void init(Channel channel) throws Exception {
     
        final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
     
            setChannelOptions(channel, options, logger);
        }

        final Map<AttributeKey<?>, Object> attrs = attrs0();
        synchronized (attrs) {
     
            for (Entry<AttributeKey<?>, Object> e: attrs.entrySet()) {
     
                @SuppressWarnings("unchecked")
                AttributeKey<Object> key = (AttributeKey<Object>) e.getKey();
                channel.attr(key).set(e.getValue());
            }
        }

        ChannelPipeline p = channel.pipeline();

        final EventLoopGroup currentChildGroup = childGroup;
        final ChannelHandler currentChildHandler = childHandler;
        final Entry<ChannelOption<?>, Object>[] currentChildOptions;
        final Entry<AttributeKey<?>, Object>[] currentChildAttrs;
        synchronized (childOptions) {
     
            currentChildOptions = childOptions.entrySet().toArray(newOptionArray(0));
        }
        synchronized (childAttrs) {
     
            currentChildAttrs = childAttrs.entrySet().toArray(newAttrArray(0));
        }

        p.addLast(new ChannelInitializer<Channel>() {
     
            @Override
            public void initChannel(final 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(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });
    }

通过 options0(); 获取到我们之前在初始化时设置的 option Map setChannelOptions 进行配置

  final Map<ChannelOption<?>, Object> options = options0();
        synchronized (options) {
     
            setChannelOptions(channel, options, logger);
        }

这里将 NioServerSocketChannel 的 pipline 进行了添加

p.addLast(new ChannelInitializer<Channel>() {
     
            @Override
            public void initChannel(final 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(
                                ch, currentChildGroup, currentChildHandler, currentChildOptions, currentChildAttrs));
                    }
                });
            }
        });

向 NioServerSocketChannel 中的 DefaultChannelPipeline 中添加了 ChannelInitializer
初始化了 private static class ServerBootstrapAcceptor extends ChannelInboundHandlerAdapter 这是 ServerBootstrapAcceptor 的内部类。

这里稍微补齐一下之前画的图,强化一下记忆

对话写 Netty 代码的同学,你真的懂 Netty 了吗?(三)看完你就无敌了 上_第6张图片
3.ChannelFuture regFuture = config().group().register(channel);

这里就相当于调用了 group.register(channel) 这个 group 就是我们初始化时 的 bossGroup 即 NioEventLoopGroup

那么 register 的实现是在其父类 MultithreadEventLoopGroup

    @Override
    public ChannelFuture register(Channel channel) {
     
        return next().register(channel);
    }

写在后面

看了下篇幅,已经够长了,不能再写了,再写又臭又长,所以决定分上下两部来走。
本篇就先到这里,下篇将继续跟进 config().group().register(channel) 以及第二部分 doBind0()
希望本文对你有所帮助。

我是 dying 搁浅 ,我始终期待与你的相遇。无论你是否期待,潮涨潮落,我仅且就在这里…

我们下期再见~
在这里插入图片描述

你可能感兴趣的:(Netty,netty,源码,硬核)