书中提到这样的一段话:
为什么在服务器中不使用SimpleChannelInboundHandler呢?因为服务器要返回相同的消息给客户端,在服务器执行完成写操作之前不能释放调
用读取到的消息,因为写操作是异步的,一旦写操作完成后,Netty中会自动释放消息。
而我们在重写SimpleChannelInboundHandler中的read0方法后,为什么会去回收其资源呢?我们可以在代码中看一下其实现:
@Override
public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
boolean release = true;
try {
if (acceptInboundMessage(msg)) {
//判断msg是否需要在此handler中做处理,需要则调用read0,然后释放msg的资源
@SuppressWarnings("unchecked")
I imsg = (I) msg;
channelRead0(ctx, imsg);
} else {
release = false;
ctx.fireChannelRead(msg);
}
} finally {
if (autoRelease && release) {
ReferenceCountUtil.release(msg);
}
}
}