05-Channel实现之AbstractChannel

Channel实现之AbstractChannel

  • AbstractChannel是Channel接口的骨架实现,Channel接口的许多派生子类几乎都直接或者间接继承了AbstractChannel,本文先分析AbstractChannel,后续分析具体的实现类时,我们会看到这样的继承关系,下面是SocketChannel接口的实现类和AbstractChannel的继承关系。

在这里插入图片描述

一、关键属性

  • AbstractChannel是继承自Channel接口,在Channel接口中定义了很多只读方法来读取相关的属性,这个我们在 04-Channel接口 中有简单分析,其中很多属性就是下面这些关键属性
{
    //父Channel对象
    private final Channel parent;
    
    //Channel 编号
    private final ChannelId id;
    
    //Unsafe 对象
    private final Unsafe unsafe;
    
    //DefaultChannelPipeline 对象
    private final DefaultChannelPipeline pipeline;
    private final VoidChannelPromise unsafeVoidPromise = new VoidChannelPromise(this, false);
    private final CloseFuture closeFuture = new CloseFuture(this);

    //本地地址
    private volatile SocketAddress localAddress;
    
    //远端地址
    private volatile SocketAddress remoteAddress;
    
    //EventLoop 对象
    private volatile EventLoop eventLoop;
    
    //是否注册
    private volatile boolean registered;
    
    //关闭是否已经初始化
    private boolean closeInitiated;
}

二、构造方法

  • AbstractChannel有两个重载的构造方法,两个构造方法差不多;
{
    /**
     * @param parent  the parent of this channel. {@code null} if there's no parent.
     */
    protected AbstractChannel(Channel parent) {
        this.parent = parent;
        //1.创建ChannelId对象,对应Channel编号
        id = newId();
        //2.创建Unsafe对象,使用在Channel的生命周期
        unsafe = newUnsafe();
        //3.创建ChannelPipeline对象,是子类DefaultChannelPipeline的实例
        pipeline = newChannelPipeline();
    }

    /**
     * @param parent the parent of this channel. {@code null} if there's no parent.
     */
    protected AbstractChannel(Channel parent, ChannelId id) {
        this.parent = parent;
        this.id = id;
        unsafe = newUnsafe();
        pipeline = newChannelPipeline();
    }
}

三、其他方法

3.1 属性读取方法

  • 这些方法基本上都是继承自Channel接口的,返回内部属性,因篇幅原因只部分方法列举如下:
{
    /**
     * 返回id
     * */
    @Override
    public final ChannelId id() {
        return id;
    }
    
    /**
     * 是否可写
     * */
    @Override
    public boolean isWritable() {
        ChannelOutboundBuffer buf = unsafe.outboundBuffer();
        return buf != null && buf.isWritable();
    }
        
    /**
     * 返回parent
     * */
    @Override
    public Channel parent() {
        return parent;
    }

    /**
     * 返回pipeline
     * */
    @Override
    public ChannelPipeline pipeline() {
        return pipeline;
    }
    
    /**
     * 返回localAddress
     * */
    @Override
    public SocketAddress localAddress() {
        SocketAddress localAddress = this.localAddress;
        if (localAddress == null) {
            try {
                this.localAddress = localAddress = unsafe().localAddress();
            } catch (Throwable t) {
                // Sometimes fails on a closed socket in Windows.
                return null;
            }
        }
        return localAddress;
    }
}
  • 涉及到比较底层的操作,比如remoteAddress和localAddress的初始化,内部是调用Unsafe对象来操作的。

3.2 IO操作方法

  • IO操作相关的方法,比如read、write、bind、connect等。这些方法内部都是由DefaultChannelPipeline来完成的,部分方法如下:
{
    /**
     * 绑定
     * */
    @Override
    public ChannelFuture bind(SocketAddress localAddress) {
        return pipeline.bind(localAddress);
    }

    /**
     * 连接
     * */
    @Override
    public ChannelFuture connect(SocketAddress remoteAddress) {
        return pipeline.connect(remoteAddress);
    }

    /**
     * 关闭
     * */
    @Override
    public ChannelFuture close() {
        return pipeline.close();
    }

    /**
     * 注销
     * */
    @Override
    public ChannelFuture deregister() {
        return pipeline.deregister();
    }

    /**
     * 读取数据
     * */
    @Override
    public Channel read() {
        pipeline.read();
        return this;
    }

    /**
     * 写数据
     * */
    @Override
    public ChannelFuture write(Object msg) {
        return pipeline.write(msg);
    }
}
  • 其他还有flush、deregister、writeAndFlush,以及其他重载方法未列举,基本上也是通过pipeline来完成的。

3.3 protected方法

  • protected方法主要是AbstractChannel定义好交给子类去实现的,通常不同的子类会有不同的实现,部分方法如下
{
    //EventLoop和实例兼容时返回true
    protected abstract boolean isCompatible(EventLoop loop);

    //返回本地绑定的SocketAddress
    protected abstract SocketAddress localAddress0();

    //返回Channel连接的远程地址
    protected abstract SocketAddress remoteAddress0();

    //Channel注册到EventLoop会调用该方法,子类实现
    protected void doRegister() throws Exception {
        // NOOP
    }

    //Channel绑定到SocketAddress
    protected abstract void doBind(SocketAddress localAddress) throws Exception;

    //断开Channel
    protected abstract void doDisconnect() throws Exception;

    //关闭Channel
    protected abstract void doClose() throws Exception;

    //Channel从EventLoop注销
    protected void doDeregister() throws Exception {
        // NOOP
    }

    //开始读数据
    protected abstract void doBeginRead() throws Exception;

    //开始写数据
    protected abstract void doWrite(ChannelOutboundBuffer in) throws Exception;
}

3.4 其他方法

  • 其他方法补充一下compareTo方法,AbstractChannel间接实现了Comparable接口,内部是通过比较ChannelId来判断两个Channel对象是否一致的。hashCode也是返回ChannelId的哈希码
  • equals和hashCode
    @Override
    public final int hashCode() {
        return id.hashCode();
    }

    @Override
    public final boolean equals(Object o) {
        return this == o;
    }

    @Override
    public final int compareTo(Channel o) {
        if (this == o) {
            return 0;
        }

        return id().compareTo(o.id());
    }
  • 另外toString方法比较长,这里就不给出代码,有兴趣可以看源码

四、AbstractUnsafe

  • AbstractUnsafe实现了Unsafe接口,AbstractChannel在初始化的时候会通过newUnsafe()方法初始化好unsafe属性,需要注意的是newUnsafe()方法是需要子类实现的,由此我推测这个Unsafe对象和平台有一定的关联,比如下面是newUnsafe()方法在EpollSocketChannel中的实现
    @Override
    protected AbstractEpollUnsafe newUnsafe() {
        return new EpollSocketChannelUnsafe();
    }
  • EpollSocketChannelUnsafe继承了AbstractEpollUnsafe,在AbstractEpollUnsafe中可以看到很多Native方法,这里就不深入了

4.1 AbstractUnsafe实现Unsafe

  • AbstractUnsafe对于Unsafe有点像AbstractChannel对于Channel,都是骨架基本实现。
  • AbstractUnsafe实现了Unsafe,虽然重写了几乎所有的方法,但是有些方法并没有直接实现,其内部是依赖Channel的方法,比如下面的localAddress()和remoteAddress(),内部调用的方法就是Channel中定义好的,需要子类实现;
    @Override
        public final SocketAddress localAddress() {
            return localAddress0();
        }

        @Override
        public final SocketAddress remoteAddress() {
            return remoteAddress0();
        }
    
    /**
     * Returns the {@link SocketAddress} which is bound locally.
     * 返回本地绑定的SocketAddress
     */
    protected abstract SocketAddress localAddress0();

    /**
     * Return the {@link SocketAddress} which the {@link Channel} is connected to.
     * 返回Channel连接的远程地址
     */
    protected abstract SocketAddress remoteAddress0();
  • AbstractUnsafe就把骨架实现好了,依赖的原语操作也交给子类实现。

4.2 AbstractUnsafe方法

  • AbstractUnsafe采用了模板模式(其实几乎所有的骨架式源码都采用了模板模式),模板方法是在AbstractUnsafe中已经实现好的骨架方法,但是依赖子类的原语操作。这里看一个register方法;register方法继承自Unsafe,真正的注册逻辑在register0中实现,
  • register方法
@Override
        public final void register(EventLoop eventLoop, final ChannelPromise promise) {
            //1.校验传入的eventLoop参数吗,不能为空
            if (eventLoop == null) {
                throw new NullPointerException("eventLoop");
            }
            //2.校验未注册,已经注册了就返回
            if (isRegistered()) {
                promise.setFailure(new IllegalStateException("registered to an event loop already"));
                return;
            }
            //3.校验Channel和eventLoop匹配兼容,isCompatible方法需要子类实现
            if (!isCompatible(eventLoop)) {
                promise.setFailure(new IllegalStateException("incompatible event loop type: " + eventLoop.getClass().getName()));
                return;
            }

            //4.设置Channel的eventLoop属性,将二者关联起来
            AbstractChannel.this.eventLoop = eventLoop;

            //5.在EventLoop中执行注册逻辑,如果当前线程就在EventLoop中,就直接注册,否则使用eventLoop线程池注册
            if (eventLoop.inEventLoop()) {
                //6.直接注册
                register0(promise);
            } else {
                //7.线程池注册
                try {
                    eventLoop.execute(new Runnable() {
                        @Override
                        public void run() {
                            System.out.println(Thread.currentThread() + ": register");
                            register0(promise);
                        }
                    });
                } catch (Throwable t) {
                    //异常处理
                    logger.warn("Force-closing a channel whose registration task was not accepted by an event loop: {}", AbstractChannel.this, t);
                    closeForcibly();
                    closeFuture.setClosed();
                    safeSetFailure(promise, t);
                }
            }
        }
  • register0方法
private void register0(ChannelPromise promise) {
            try {
                // check if the channel is still open as it could be closed in the mean time when the register
                // call was outside of the eventLoop
                //1.判断channel仍然是打开的,反之就返回
                if (!promise.setUncancellable() // TODO 1001 Promise
                        || !ensureOpen(promise)) {
                    return;
                }
                //2.记录是否为首次注册
                boolean firstRegistration = neverRegistered;

                //3.执行注册逻辑,原语操作,交给子类去实现
                doRegister();

                //4.标记首次注册为false
                neverRegistered = false;
                //5.标记Channel为已注册
                registered = true;

                // Ensure we call handlerAdded(...) before we actually notify the promise. This is needed as the
                // user may already fire events through the pipeline in the ChannelFutureListener.
                //6.在通知promise之前调用handlerAdded,因为用户有可能在ChannelFutureListener通过pipeline fire事件(现在还不甚理解)
                pipeline.invokeHandlerAddedIfNeeded();

                //7.回调通知promise执行成功
                safeSetSuccess(promise);

                //8.触发通知已注册事件
                pipeline.fireChannelRegistered();

                //9.首次注册的话,就fire一个channelActive,这样如果是注销再注册的话就不会触发多个channel actives事件
                // Only fire a channelActive if the channel has never been registered. This prevents firing
                // multiple channel actives if the channel is deregistered and re-registered.
                if (isActive()) {
                    if (firstRegistration) {
                        pipeline.fireChannelActive();
                    } else if (config().isAutoRead()) {
                        // This channel was registered before and autoRead() is set. This means we need to begin read
                        // again so that we process inbound data.
                        //
                        // See https://github.com/netty/netty/issues/4805
                        beginRead();
                    }
                }
            } catch (Throwable t) {
                //异常处理
                // Close the channel directly to avoid FD leak.
                closeForcibly();
                closeFuture.setClosed();
                safeSetFailure(promise, t);
            }
        }
  • 在register0方法中调用了Channel的doRegister方法,该方法需要子类实现
  • AbstractUnsafe在还实现了Unsafe接口中的很多方法,基本都是骨架实现,部分流程或者判断是调用Channel中的方法,要么AbstractChannel中已经实现好了,要么交给子类实现

五、小结

  • AbstractChannel是Channel的骨架实现、从源码来看实现的比较基本,比如将只读方法返回内部的属性,将很多基本操作交给pipleline去执行,我们只能看到一些大体的逻辑,另外AbstractUnsafe也实现了Channel的内部Unsafe接口,也做了类似的事情,将很多方法的骨架实现好,部分方法内部依赖Channel的方法,不同的子类只需要实现特定的方法,这使得子类的实现变得方便。
  • 本文其实并未深入分析AbstractChannel的源码,由其是AbstractUnsafe,有很多方法未解析,只是从整体上了解AbstractChannel以及它在整个Channel继承体系中的作用
  • 后续的文章,我们会根据Channel的子接口类型来分析其具体的实现类,它们基本上都是AbstractChannel的子类
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值