我正在为我的项目制作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;
}
}
Run Code Online (Sandbox Code Playgroud)
我在管道中有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;
}
}
Run Code Online (Sandbox Code Playgroud)
我认为如果您实现自己的 FrameDecoder,您将获得最佳性能。这将允许您缓冲所有数据,直到您确实需要将其分派到链中的下一个处理程序。请参阅FrameDecoder apidocs。
如果您不想自己处理 CRLF 的检测,也可以保留 DelimiterBasedFrameDecoder 并在其后面添加一个自定义 FrameDecoder 来组装表示一行文本的 ChannelBuffer。
在这两种情况下,FrameDecoder 都会尝试“包装”缓冲区而不是每次都复制它们,从而尽可能减少内存复制。
也就是说,如果您想获得最佳性能,请使用第一种方法,如果您想要轻松,请使用第二种方法;)
归档时间: |
|
查看次数: |
1945 次 |
最近记录: |