java – 在处理程序中组装一个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构造. (这给出了最差的内存性能.事实上,对于具有大量并发用户的大型有效负载,这会产生不可接受的性能) 我是Netty的新手,我可能在架构上做错了.非常感谢您的意见. 提前致谢 添加我的自定义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都会尽量减少内存副本,尝试只是“包装”缓冲区而不是每次都复制它们. 也就是说,如果你想拥有最好的性能,那就选择第一种方法,如果你想轻松实现第二种方法;) (编辑:安卓应用网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |
