Handler & Pipeline

ChannelHandler 用来处理 Channel 上的各种事件,分为入站、出站两种。所有 ChannelHandler 被连成一串,就是 Pipeline

  • 入站处理器通常是 ChannelInboundHandlerAdapter 的子类,主要用来读取客户端数据,写回结果
  • 出站处理器通常是 ChannelOutboundHandlerAdapter 的子类,主要对写回结果进行加工

打个比喻,每个 Channel 是一个产品的加工车间,Pipeline 是车间中的流水线,ChannelHandler 就是流水线上的各道工序,而后面要讲的 ByteBuf 是原材料,经过很多工序的加工:先经过一道道入站工序,再经过一道道出站工序最终变成产品

ChannelInboundHandlerAdapter 是按照 addLast 的顺序执行的,而 ChannelOutboundHandlerAdapter 是按照 addLast 的逆序执行的。

ChannelPipeline 的实现是一个 ChannelHandlerContext(包装了 ChannelHandler) 组成的双向链表

ChannelHandlerContext的之间是双向链表,如果有写出操作,则出站处理器是按addLast逆序执行。

public class DefaultChannelPipeline implements ChannelPipeline {
// head 和tail
final AbstractChannelHandlerContext head;
final AbstractChannelHandlerContext tail;
private final Channel channel;
private final ChannelFuture succeededFuture;
// addLast
private void addLast0(AbstractChannelHandlerContext newCtx) {
AbstractChannelHandlerContext prev = tail.prev;
newCtx.prev = prev;
newCtx.next = tail;
prev.next = newCtx;
tail.prev = newCtx;
}
}

Netty Pipeline

演示:

后续说明以h1、h2、h3都作为入站处理器、而h4、h5、h6都作为出站处理器

在每个不是最后的入站处理器中,我们必须调用channelRead方法,否则链就断了。 在重写的方法里,如果不调用 super.channelRead(...) 或 ctx.fireChannelRead(...),事件就会在此处拦截,后续的 Handler 将不会收到该事件

在handler-3,也就是最后一个入站处理器的方法中,不需要再调用super.channelRead(),因为后面没有入站处理器了。直接调用写出的方法

/**
* @Author: yakiniku
* @Date: created on 2021/12/5 02:13
*/
@Slf4j
public class TestPipeLine {
public static void main(String[] args) {
new ServerBootstrap()
.group(new NioEventLoopGroup())
.channel(NioServerSocketChannel.class)
.childHandler(new ChannelInitializer<NioSocketChannel>() {
@Override
protected void initChannel(NioSocketChannel ch) throws Exception {
// 通过channel拿到pipeline
ChannelPipeline pipeline = ch.pipeline();
// 添加处理器 netty会默认有两个head 和tail
// head -> h1 -> h2-> h3->... -> tail
// head -> h1 -> h2-> h3-> out-h4-> h5 -> h6.... -> tail
pipeline.addLast("handler-1",new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.debug("1");
ByteBuf buf = (ByteBuf) msg;
String name = buf.toString(Charset.defaultCharset());
super.channelRead(ctx, name);
}
});
pipeline.addLast("handler-2",new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.debug("2");
String name = (String) msg;
Student student = new Student(name);
super.channelRead(ctx, student);
}
});
pipeline.addLast("handler-3",new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.debug("3,结果{},class{}",msg,msg.getClass());
//不需要继续调用super.channelRead ,因为后面没有入站处理器了。
// super.channelRead(ctx, msg);
// ch.writeAndFlush("test"); //这条收不到= = 但是Outbound里的都会执行到
ch.writeAndFlush(ctx.alloc().buffer().writeBytes("server..".getBytes()));
}
});
pipeline.addLast("handler-4",new ChannelOutboundHandlerAdapter(){
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
log.debug("4");
super.write(ctx, msg, promise);
}
});
pipeline.addLast("handler-5",new ChannelOutboundHandlerAdapter(){
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
log.debug("5");
super.write(ctx, msg, promise);
}
});
pipeline.addLast("handler-6",new ChannelOutboundHandlerAdapter(){
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
log.debug("6");
super.write(ctx, msg, promise);
}
});
}
})
.bind(9070);
}
@Data
@AllArgsConstructor
static class Student{
private String name;
}
}
22:06:26.742 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 1
22:06:26.748 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 2
22:06:26.749 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 3,结果TestPipeLine.Student(name=小明),classclass com.yakiniku.netty.c4.TestPipeLine$Student
22:06:26.750 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 6
22:06:26.750 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 5
22:06:26.750 [nioEventLoopGroup-2-2] DEBUG com.yakiniku.netty.c4.TestPipeLine - 4

channel的writeAndFlush的方法和直接调用channelHandlerContext的writeAndFlush方法有什么不同?

首先,如果在入站处理器调用channel.writeAndFlush(),实际上会从tail开始往前调用出站处理器

@Override
public final ChannelFuture writeAndFlush(Object msg) {
return tail.writeAndFlush(msg);
}

而如果直接调用ctx.writeAndFlush(),则是直接从当前handler往前找出站处理器。

channel : h1→h2→h3→tail→h6→h5→h4

ctx : h1→h2→h3

如果一开始的顺序是: h1←→h2←→h4←→h3←→h5←→h6,那么

ctx :h1→h2→h3→h4

EmbeddedChannel

EmbeddedChannel 是 Netty 提供的一个专门用于测试和在无网络传输环境下运行 ChannelHandler/Pipeline 的特殊 Channel 实现。 它把原本依赖真实底层网络 I/O(如 TCP Socket、NIO 等)的异步事件流,封装到了内存中的队列中, 允许开发者以同步、可控的方式模拟入站(Inbound)和出站(Outbound)的数据收发。

核心应用场景

  • 单元测试自定义Handler,如测试自定义编码器解码器,协议解析,加解密,业务处理Handler等,无需启动真实的Socket服务端或客户端
  • 免端口、轻量级运行
/**
* @Author: yakiniku
* @Date: created on 2021/12/5 22:38
*/
@Slf4j
public class TestEmbeddedChannel {
public static void main(String[] args) {
ChannelInboundHandlerAdapter h1 = new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.debug("1");
super.channelRead(ctx,msg);
}
};
ChannelInboundHandlerAdapter h2 = new ChannelInboundHandlerAdapter() {
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.debug("2");
super.channelRead(ctx, msg);
}
};
ChannelOutboundHandlerAdapter h3 = new ChannelOutboundHandlerAdapter(){
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
log.debug("3");
super.write(ctx, msg, promise);
}
};
ChannelOutboundHandlerAdapter h4 = new ChannelOutboundHandlerAdapter(){
@Override
public void write(ChannelHandlerContext ctx, Object msg, ChannelPromise promise) throws Exception {
log.debug("4");
super.write(ctx, msg, promise);
}
};
EmbeddedChannel embeddedChannel = new EmbeddedChannel(h1, h2, h3, h4);
//模拟入站操作
embeddedChannel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes()));
embeddedChannel.writeOutbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("world".getBytes()));
}
}
22:52:11.116 [main] DEBUG c.y.netty.c4.TestEmbeddedChannel - 1
22:52:11.118 [main] DEBUG c.y.netty.c4.TestEmbeddedChannel - 2
22:52:11.120 [main] DEBUG c.y.netty.c4.TestEmbeddedChannel - 4
22:52:11.120 [main] DEBUG c.y.netty.c4.TestEmbeddedChannel - 3

异常捕获机制

在复杂的Pipeline中,如果某个Handler抛出了异常,这个异常会沿着Pipeline顺次向后传播,直到被某个实现了exceptionCaught方法的Handler捕获。

最佳实践:通常在Pipeline的最后一个Handler(紧挨着tail之前)实现统一的异常处理逻辑(如打印日志、关闭连接、向客户端写回错误码)。如果在中途的 Handler 捕获了异常但没有向后传递,或者没有做任何处理,可能会导致异常被吞掉或连接无法正常释放。

演示代码

public class EmbeddedChannelDemo {
private static final Logger log = Logger.getLogger(EmbeddedChannelDemo.class.getName());
public static void main(String[] args) {
ChannelInboundHandlerAdapter h1 = new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("h1");
super.channelRead(ctx, msg);
}
};
ChannelInboundHandlerAdapter h2 = new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("h2");
// 这里触发一个除零异常
int i = 1/0;
super.channelRead(ctx, msg);
}
};
ChannelInboundHandlerAdapter h3 = new ChannelInboundHandlerAdapter(){
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
log.info("h3");
super.channelRead(ctx, msg);
}
public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
log.info("捕获到异常: "+cause.getMessage());
}
};
EmbeddedChannel embeddedChannel = new EmbeddedChannel(h1, h2, h3);
embeddedChannel.writeInbound(ByteBufAllocator.DEFAULT.buffer().writeBytes("hello".getBytes()));
}
}