Netty源码解析(七) —— Pipeline的工作机制

本文深入探讨Netty的Pipeline,揭示其内部双向环形链表的结构,包括HeadContext和TailContext。内容涵盖Pipeline的构造过程,如何添加节点,以及防止重复添加Handler的机制。当客户端连接到服务端时,Pipeline的构建和HandlerContext节点的装配过程也在文中详细解析,特别指出ServerBootstrapAcceptor的角色。此外,文章还解释了原生Java通道如何被包装成Netty的NioSocketChannel。
摘要由CSDN通过智能技术生成

Pipeline是一个由HandlerContext节点构成的双向环形链表,结构如下图,最前面是HeadContext,末尾是TailContext中间是用户自定义的HandlerContext节点

这里写图片描述
先来看pipLine的构造参数

    /**
     * channelPipLine的默认构造方法
     * @param channel
     */
    protected DefaultChannelPipeline(Channel channel) {
        this.channel = ObjectUtil.checkNotNull(channel, "channel");
        succeededFuture = new SucceededChannelFuture(channel, null);
        voidPromise =  new VoidChannelPromise(channel, true);

        //创建TailContext
        tail = new TailContext(this);
        //创建HeadContext
        head = new HeadContext(this);

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

可以看到pipline默认创建一个head和tail并且组成一个双向链表,而pipline的创建需要一个channel作为参数,实际上pipline是在channel里面创建的(即一个channel对应一个pipline)
pipline的添加节点方法

    public final ChannelPipeline addLast(ChannelHandler handler) {
        return addLast(null, handler);
    }

最终调用到

    @Override
    public final ChannelPipeline addLast(EventExecutorGroup group, String name, ChannelHandler handler) {
        final AbstractChannelHandlerContext newCtx;
        synchronized (this) {
            //检查handler是否重复添加
            checkMultiplicity(handler);

            //创建pipLine节点
            newCtx = newContext(group, filterName(name, handler), handler);
            //添加节点操作
            addLast0(newCtx);

            if (!registered) {
                newCtx.setAddPending();
                callHandlerCallbackLater(newCtx, true);
                return this;
            }

            EventExecutor executor = newCtx.executor();
            //判断当前线程是否是NioEventLoop运行线程
            if (!executor.inEventLoop()) {
                newCtx.setAddPending();
                executor.execute(new Runnable() {
                    @Override
                    public void run() {
                        //调用hander的add方法
                        callHandlerAdded0(newCtx);
                    }
                });
                return this;
            }
        }
        callHandlerAdded0(newCtx);
        return this;
    }
  1. 检查handler是否重复添加
  2. 创建pipLine节点<
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值