本文介绍了当我必须在Netty4编码器中调用ByteBuf.retain()时?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我正在编写一个NUL-终止JSON消息的编码器,以便在消息被分段的情况下对其进行解码。I am writing a Encoder that NUL-Terminates a JSON-Message so it can be decoded in case the message is fragmented.我找到了这个样本 - > 点击 where 最后调用ByteBuf.retain()将现有的ByteBuf写入输出。为什么他们这样做,为什么需要呢?I found this sample ->click where ByteBuf.retain() was called in the end to write an existing ByteBuf to the output. Why did they do that, and why is it needed?这是我的编码器: Here's my Encoder:public class FrameEncoder extends MessageToMessageEncoder<ByteBuf> { @Override protected void encode(ChannelHandlerContext ctx, ByteBuf msg, List<Object> out) throws Exception { out.add(msg.retain()); out.add(ctx.alloc().buffer(1).writeByte(NUL)); }} 推荐答案默认 MessageToMessageEncoder 发布编码后的原始邮件。当编码器因编码返回新消息时,它与 MessageToMessageEncoder 的典型用例一致,因此可以在编码后安全地丢弃原始消息。By default MessageToMessageEncoder releases original message after encoding. It's consistent with the typical use case of MessageToMessageEncoder, when your encoder returns new message as a result of encoding, so that original message can be safely discarded after encoding.但是,当原始消息用作结果的一部分时,不应该丢弃原始消息,就像你的情况一样。在这种情况下,您需要显式调用 retain()。However, orginal message should not be discarded when it's used as a part of the result, as in your case. In this case you need to call retain() explicitly.来自 javadoc MessageToMessageEncoder : 请注意,如果它们的类型为ReferenceCounted,则需要对刚刚传递的消息调用ReferenceCounted.retain()。这是必需的,因为MessageToMessageEncoder将在编码消息上调用ReferenceCounted.release()。 Be aware that you need to call ReferenceCounted.retain() on messages that are just passed through if they are of type ReferenceCounted. This is needed as the MessageToMessageEncoder will call ReferenceCounted.release() on encoded messages. 这篇关于当我必须在Netty4编码器中调用ByteBuf.retain()时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!
10-14 15:58