在处理程序中组装一个Netty消息

我正在为我的项目制作Netty原型。 我试图在Netty上实现一个简单的面向文本/字符串的协议。 在我的管道中,我使用以下内容:

public class TextProtocolPipelineFactory implements ChannelPipelineFactory { @Override public ChannelPipeline getPipeline() throws Exception { // Create a default pipeline implementation. ChannelPipeline pipeline = pipeline(); // Add the text line codec combination first, pipeline.addLast("framer", new DelimiterBasedFrameDecoder(2000000, Delimiters.lineDelimiter())); pipeline.addLast("decoder", new StringDecoder()); pipeline.addLast("encoder", new StringEncoder()); // and then business logic. pipeline.addLast("handler", new TextProtocolHandler()); return pipeline; } } 

我在管道中有DelimiterBasedFrameDecoder,String Decoder和String Encoder。

由于此设置,我的传入消息被拆分为多个字符串。 这导致我的处理程序的“messageReceived”方法的多次调用。 这可以。 但是,这需要我在内存中累积这些消息,并在收到消息的最后一个字符串数据包时重新构造消息。

我的问题是,什么是“积累字符串”然后“将它们重新构造成最终消息”的最有效的内存方式。 到目前为止我有3个选项。 他们是:

  • 使用StringBuilder累积和toString来构造。 (这给出了最差的内存性能。事实上,对于具有大量并发用户的大型有效负载,这会产生不可接受的性能)

  • 通过ByteArrayOutputStream累积到ByteArray中,然后使用字节数组构造(这提供了比选项1更好的性能,但它仍然占用了相当多的内存)

  • 累积到Dymamic Channel Buffer并使用toString(charset)来构造。 我还没有介绍过这个设置,但我很好奇这与上面两个选项相比如何。 有没有人使用动态通道缓冲区解决了这个问题?

我是Netty的新手,我可能在架构上做错了。 非常感谢您的意见。

在此先感谢Sohil

添加我的自定义FrameDecoder实现供Norman审查

 public final class TextProtocolFrameDecoder extends FrameDecoder { public static ChannelBuffer messageDelimiter() { return ChannelBuffers.wrappedBuffer(new byte[] {'E','O','F'}); } @Override protected Object decode(ChannelHandlerContext ctx, Channel channel,ChannelBuffer buffer) throws Exception { int eofIndex = find(buffer, messageDelimiter()); if(eofIndex != -1) { ChannelBuffer frame = buffer.readBytes(buffer.readableBytes()); return frame; } return null; } private static int find(ChannelBuffer haystack, ChannelBuffer needle) { for (int i = haystack.readerIndex(); i < haystack.writerIndex(); i ++) { int haystackIndex = i; int needleIndex; for (needleIndex = 0; needleIndex < needle.capacity(); needleIndex ++) { if (haystack.getByte(haystackIndex) != needle.getByte(needleIndex)) { break; } else { haystackIndex ++; if (haystackIndex == haystack.writerIndex() && needleIndex != needle.capacity() - 1) { return -1; } } } if (needleIndex == needle.capacity()) { // Found the needle from the haystack! return i - haystack.readerIndex(); } } return -1; } } 

如果您要实现自己的FrameDecoder,我认为您将获得最佳性能。 这将允许您缓冲所有数据,直到您真正需要将其分派给链中的下一个处理程序。 请参考FrameDecoder apidocs。

如果您不想自己处理CRLF的检测,也可以保留DelimiterBasedFrameDecoder并在其后面添加一个自定义FrameDecoder来组装表示一行文本的ChannelBuffers。

在这两种情况下,FrameDecoder都会尽可能地通过尝试“包装”缓冲区而不是每次都复制它们来尽量减少内存副本。

也就是说,如果你想拥有最好的性能,那就选择第一种方法,如果你想轻松实现第二种方法;)