Netty 之 AbstractNioByteChannel 源码分析

Netty 版本:4.1.33.Final-SNAPSHOT

AbstractNioByteChannel

public abstract class AbstractNioByteChannel extends AbstractNioChannel {

    // 负责刷新发送缓存链表中的数据
    private final Runnable flushTask = new Runnable() {
        @Override
        public void run() {
            // Calling flush0 directly to ensure we not try to flush messages that were added via write(...) in the
            // meantime.
            ((AbstractNioUnsafe) unsafe()).flush0();
        }
    };
    
    // 
    protected AbstractNioByteChannel(Channel parent, SelectableChannel ch) {
        super(parent, ch, SelectionKey.OP_READ);
    }

    // NioByteUnsafe 重写了 AbstractNioUnsafe 类中的读取方法
    @Override
    protected AbstractNioUnsafe newUnsafe() {
        return new NioByteUnsafe();
    }

1、该类定义了一个 flushTask 变量,来负责刷新发送已经 write 到缓存中的数据。write 的数据没有直接写到 socket 中,而是写入到 ChannelOutboundBuffer 缓存中,等 flush 的时候才会写到 Socket 中进行发送数据。
2、AbstractNioByteChannel 定义了 NioByteUnsafe 类。
NioByteUnsafe 类继承了 AbstractNioChannel 的内部类 AbstractNioUnsafe,并重写了读取数据的方法。


AbstractNioByteChannel 类主要定义了写入消息的 doWrite() 方法,下面我们主要分析发送消息的 doWrite() 方法。

doWrite() 方法

@Override
protected void doWrite(ChannelOutboundBuffer in) throws Exception {
    // 获取循环发送的次数
    int writeSpinCount = config().getWriteSpinCount();
    do {
        // 获取写缓存链表中第一条要写入的数据
        Object msg = in.current();
        // 如果没有要写入的数据,取消注册到 selector 上的 OP_WRITE 事件。
        if (msg == null) {
            // Wrote all messages.
            clearOpWrite();
            // Directly return here so incompleteWrite(...) is not called.
            return;
        }
        // 写入消息
        writeSpinCount -= doWriteInternal(in, msg);
    } while (writeSpinCount > 0);
    // 如果未发送完成则在 selector 上注册 OP_WRITE 事件。
    // 如果发送完成则在 selector 上取消 OP_WRITE 事件。
    incompleteWrite(writeSpinCount < 0);
}

1、首先获取循环发送的次数,默认为16次 private volatile int writeSpinCount = 16。当一次没有完成该消息的发送的时候(写半包),会继续循环发送。
设置发送循环的最大次数原因是当循环发送的时候,I/O 线程会一直尝试进行写操作,此时I/O 线程无法处理其他的 I/O 操作,比如发送消息,而客户端接收数据比较慢,这事会一直不停的尝试给客户端发送数据。

2、从 ChannelOutboundBuffer 中获取待写入到 Socket 中的消息。
Netty 写数据的时候首先是把数据写入到 ChannelOutboundBuffer 缓存中。使用的链表保存写入的消息数据。当调用 flush 的时候会从 ChannelOutboundBuffer 缓存中获取数据写入到 Socket 中发送出去。

3、当获取消息为空,说明所有数据都已经发送出去。然后调用 clearOpWrite(),取消该 Channel 注册在 Selector 上的 OP_WRITE 事件。

4、调用 doWriteInternal() 方法写入消息

5、incompleteWrite() 方法判断消息是否写入完成,然后做相关的操作。
如果未发送完成则在 selector 上注册 OP_WRITE 事件。
如果发送完成则在 selector 上取消 OP_WRITE 事件。

clearOpWrite() 清除写标识

protected final void clearOpWrite() {
    final SelectionKey key = selectionKey();
    // Check first if the key is still valid as it may be canceled as part of the deregistration
    // from the EventLoop
    // See https://github.com/netty/netty/issues/2104
    if (!key.isValid()) {
        return;
    }
    final int interestOps = key.interestOps();
    if ((interestOps & SelectionKey.OP_WRITE) != 0) {
        key.interestOps(interestOps & ~SelectionKey.OP_WRITE);
    }
}

该方法主要是清除该 Channel 在 Selector 上的注册的 OP_WRITE 事件。

doWriteInternal() 发送消息

private int doWriteInternal(ChannelOutboundBuffer in, Object msg) throws Exception {
    if (msg instanceof ByteBuf) {
        ByteBuf buf = (ByteBuf) msg;
        // 1
        if (!buf.isReadable()) {
            in.remove();
            return 0;
        }
        // 2
        final int localFlushedAmount = doWriteBytes(buf);
        if (localFlushedAmount > 0) {
            // 3
            in.progress(localFlushedAmount);
            // 4
            if (!buf.isReadable()) {
                in.remove();
            }
            return 1;
        }
    } else if (msg instanceof FileRegion) {
        FileRegion region = (FileRegion) msg;
        if (region.transferred() >= region.count()) {
            in.remove();
            return 0;
        }

        long localFlushedAmount = doWriteFileRegion(region);
        if (localFlushedAmount > 0) {
            in.progress(localFlushedAmount);
            if (region.transferred() >= region.count()) {
                in.remove();
            }
            return 1;
        }
    } else {
        // Should not reach here.
        throw new Error();
    }
    return WRITE_STATUS_SNDBUF_FULL;
}

发送消息可以支持两种类型 ByteBuf 和 FileRegion。这里只分析 ByteBuf。FileRegion 和 ByteBuf 发送类似。

1、首先判断 buf 是否可读,如果不可读,说明该消息不可用,直接丢弃,并且在 ChannelOutboundBuffer 的缓存链表中删除该消息 。然后在 doWrite 继续循环发送下一条消息。
2、如果 buf 可读,则调用 doWriteBytes() 方法发送消息,直接写到 Socket 中发送出去,并且返回发送的字节数。
3、如果发送的字节数大于0,则调用 in.progress() 更新消息发送的进度。
4、判断当前的 buf 中的数据是否已经全部发送完成,如果完成则从 ChannelOutboundBuffer 缓存链表中删除该消息。

该方法的返回值
1、如果从 ChannelOutboundBuffer 中获取的消息不可读,返回0,不计入循环发送的次数
2、如果调用 doWriteBytes 发送消息,只要发送的消息字节数大于0,就计入一次循环发送次数
3、如果调用 doWriteBytes 发送消息,发送的字节数为0,则返回一个WRITE_STATUS_SNDBUF_FULL = Integer.MAX_VALUE值。

一般只有当前 Socket 缓冲区写满了,无法再继续发送数据的时候才会返回0(Socket 的Buffer已满)。 如果继续循环发送也还是无法写入的,这时只见返回一个比较大值,会直接退出循环发送的,稍后再尝试写入。

incompleteWrite()

protected final void incompleteWrite(boolean setOpWrite) {
    // Did not write completely.
    if (setOpWrite) {
        setOpWrite();
    } else {
        // It is possible that we have set the write OP, woken up by NIO because the socket is writable, and then
        // use our write quantum. In this case we no longer want to set the write OP because the socket is still
        // writable (as far as we know). We will find out next time we attempt to write if the socket is writable
        // and set the write OP if necessary.
        clearOpWrite();

        // Schedule flush again later so other tasks can be picked up in the meantime
        eventLoop().execute(flushTask);
    }
}

1、boolean setOpWrite = writeSpinCount < 0; writeSpinCount 什么时候才会出现小于0 呢?上面已经分析过,如果调用 doWriteBytes 发送消息,发送的字节数为0,则返回一个WRITE_STATUS_SNDBUF_FULL = Integer.MAX_VALUE值。Socket 的 Buffer 已经写满,无法再继续发送数据。
这说明该消息还未写完,然后调用 setOpWrite() 方法,在 Selector 上注册写标识。

2、如果写完,则清除 Selector 上注册的写标识。稍后再刷新计划,以便同时处理其他任务。

protected final void setOpWrite() {
    final SelectionKey key = selectionKey();
    // Check first if the key is still valid as it may be canceled as part of the deregistration
    // from the EventLoop
    // See https://github.com/netty/netty/issues/2104
    if (!key.isValid()) {
        return;
    }
    final int interestOps = key.interestOps();
    if ((interestOps & SelectionKey.OP_WRITE) == 0) {
        key.interestOps(interestOps | SelectionKey.OP_WRITE);
    }
}

首先判断 SelectionKey 是否有效
判断 Selector 上是否注册了 OP_WRITE 标识,如果没有则注册上。

猜你喜欢

转载自blog.csdn.net/weixin_34059951/article/details/86843252