Netty 中的业务处理流程都是在 Pipeline 中被处理的,它底层是一个双向链表,链表元素是ChannelInBoundHandler 和 ChannelOutBoundHandler,二者都是 ChannelHandler 接口类,一个 Channel 拥有一个 Pipeline, 当 Channel 被创建时会创建一个空的Pipeline。
public abstract class AbstractChannel implements Channel {
// Channel 初始化
public AbstractChannel(Channel parent) {
this.parent = parent;
// 新建一个空的 pipeline,并把 pipeline 和 Channel 绑定
pipeline = newChannelPipeline();
}
protected ChannelPipeline newChannelPipeline() {
return new ChannelPipeline(this);
}
}
在服务端处理连接请求时,ServerBootstrapAcceptor 这个NIOServerSocketChannel 里的ChannelInBoundHandler 类在把 NIOSocketChannel 注册到一个工作线程池里的一个EventLoop时,它会把 ChannelHandler 数组添加到这个 NIOSocketChannel 里的Pipeline里,这就完成了pipeline 底层 ChannelHandler 链表元素的添加和初始化。
private static class ServerBootstrapAcceptor implements ChannelInboundHandler {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
final Channel child = (Channel) msg;
// 把所有的 ChannelHandler 加入到 Channel 的 pipeline 里去
for (ChannelHandler childHandler : childHandlers) {
child.pipeline().addLast(childHandler);
}
// 把 Channel 注册到 workerGroup 里的一个 EventLoop 关联的 Selector
childGroup.register(child);
}
}
当 IO多路复用器 Selector 检测到读事件时,它会去读取缓冲区的字节流并包装为 ByteBuf 链表,并触发 Channel 的Read() 方法,让 Pipeline 里的 ChannelHandler 元素列表依次处理该 ByteBuf 链表,这就是责任链模式,Pipeline 的工作也就完成了。
public class NioEventLoop extends SingleThreadEventLoop {
if ((readyOps & (SelectionKey.OP_READ | SelectionKey.OP_ACCEPT)) != 0 || readyOps == 0) {
// channel 读取数据
ch.read();
}
}
public abstract class AbstractNioByteChannel extends AbstractNioChannel {
@Override
public void read() {
final ChannelPipeline pipeline = pipeline();
// 这里做了简化处理,源码用的自封装ByteBuf
ByteBuffer byteBuf = ByteBuffer.allocate(128);
// 读取数据到 byteBuf
doReadBytes(byteBuf);
// 触发pipeline处理 byteBuf,责任链模式
pipeline.fireChannelRead(byteBuf);
}
}