Netty随记之ChannelHandlerContext与Channel的writeAndFlush的区别

ChannelHandlerContext的writeAndFlush方法会将数据写到ChannelPipeline中当前ChannelHandler的下一个ChannelHandler开始处理。

ChannelHandlerContext#writeAndFlush实现源码:

private void write(Object msg, boolean flush, ChannelPromise promise) {
        AbstractChannelHandlerContext next = findContextOutbound();
        final Object m = pipeline.touch(msg, next);
        EventExecutor executor = next.executor();
        if (executor.inEventLoop()) {
            if (flush) {
                next.invokeWriteAndFlush(m, promise);
            } else {
                next.invokeWrite(m, promise);
            }
        } else {
            AbstractWriteTask task;
            if (flush) {
                task = WriteAndFlushTask.newInstance(next, m, promise);
            }  else {
                task = WriteTask.newInstance(next, m, promise);
            }
            safeExecute(executor, task, promise, m);
        }
    }

private AbstractChannelHandlerContext findContextOutbound() {
        AbstractChannelHandlerContext ctx = this;
        do {
            ctx = ctx.prev;
        } while (!ctx.outbound);
        return ctx;
    }

Channel的writeAndFlush方法会将数据写到ChannelPipeline中最后一个ChannelHandler然后数据从尾部开始向头部方向流动会经过所有的ChannelHandler, ChannelPipeline中的所有ChannelHandler都可以处理数据。

public final ChannelFuture writeAndFlush(Object msg) {
        return tail.writeAndFlush(msg);
    }
上一篇:gorm框架


下一篇:Happens-before