Netty 净值4:writeAndFlush ByteBuf和引用计数
正如《基本法》所说: 当出站(也称为下游)消息在开始时到达 对于管道,Netty将在写出后发布它 因此,在正常情况下,成功调用后,Netty 净值4:writeAndFlush ByteBuf和引用计数,netty,Netty,正如《基本法》所说: 当出站(也称为下游)消息在开始时到达 对于管道,Netty将在写出后发布它 因此,在正常情况下,成功调用后,ByteBuf的引用计数将减少 发生错误的情况如何? 假设我有两个频道:firstChannel&secondChannel。如果ByteBuf未能发送到firstChannel,则需要将其发送到secondChannel 下面是代码示例 final ChannelFuture future = firstChannel.writeAndFlush(byteBuf.a
ByteBuf
的引用计数将减少
发生错误的情况如何?
假设我有两个频道:firstChannel
&secondChannel
。如果ByteBuf
未能发送到firstChannel
,则需要将其发送到secondChannel
下面是代码示例
final ChannelFuture future = firstChannel.writeAndFlush(byteBuf.asReadOnly()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
// Is the reference count decreased already before entering this method?
if (!future.isSuccess()) {
byteBuf.retain();
secondChannel.writeAndFlush(byteBuf);
}
}
});
即使发生错误,引用计数也会减少吗?
在触发
操作完成之前,引用计数是否已减少?
即使失败,它也会释放缓冲区,使代码无法工作。您需要retain()
缓冲区,以确保在调用侦听器时增量计数为1,然后在将来成功时自行递减
大概是这样的:
final ChannelFuture future = firstChannel.writeAndFlush(byteBuf.retain().duplicate()).addListener(new ChannelFutureListener() {
@Override
public void operationComplete(ChannelFuture future) {
if (!future.isSuccess()) {
secondChannel.writeAndFlush(byteBuf);
} else {
byteBuf.release();
}
}
});
还请注意,我调用了
duplicate()
,以确保我们不会修改缓冲区的读写器索引,该索引稍后可能会传递到第二个通道。我使用的是asReadOnly()
,在这种情况下与duplicate()
相同吗?@NormanMaurer,因此,writeAndFlush总是释放缓冲区?无论发生什么情况,调用writeAndFlush总是会释放缓冲区?或者它是否存在writeAndFlush不会释放缓冲区的捕获或场景?只要“写入/刷新”未被任何ChannelOutboundHandler实现丢弃,它始终会释放缓冲区。在这种情况下,处理程序负责释放它。