高性能RPC over MINA&google protobuf 代码&实例 (二)

在本系列上篇http://maoyidao.iteye.com/blog/1636923 实现了基于google protobuf的序列化反序列化,现在看看怎么把他们组装到MINA的nio中。本篇主要描述怎么处理断包。

 

使用MINA的CumulativeProtocolDecoder是个好主意,先从MINA自己的sample开始。在这个例子中如果接受到的IoBuffer只包含一部分消息, decoders应该继续接收消息知道接收到完整的消息之后再进行解码。

List1

 

Java代码   收藏代码
  1. public class CrLfTerminatedCommandLineDecoder  
  2.          extends CumulativeProtocolDecoder {  
  3.   
  4.      private Command parseCommand(IoBuffer in) {  
  5.          // Convert the bytes in the specified buffer to a  
  6.          // Command object.  
  7.          ...  
  8.      }  
  9.   
  10.      protected boolean doDecode(  
  11.              IoSession session, IoBuffer in, ProtocolDecoderOutput out)  
  12.              throws Exception {  
  13.   
  14.          // Remember the initial position.  
  15.          int start = in.position();  
  16.   
  17.          // Now find the first CRLF in the buffer.  
  18.          byte previous = 0;  
  19.          while (in.hasRemaining()) {  
  20.              byte current = in.get();  
  21.   
  22.              if (previous == '\r' && current == '\n') {  
  23.                  // Remember the current position and limit.  
  24.                  int position = in.position();  
  25.                  int limit = in.limit();  
  26.                  try {  
  27.                      in.position(start);  
  28.                      in.limit(position);  
  29.                      // The bytes between in.position() and in.limit()  
  30.                      // now contain a full CRLF terminated line.  
  31.                      out.write(parseCommand(in.slice()));  
  32.                  } finally {  
  33.                      // Set the position to point right after the  
  34.                      // detected line and set the limit to the old  
  35.                      // one.  
  36.                      in.position(position);  
  37.                      in.limit(limit);  
  38.                  }  
  39.                  // Decoded one line; CumulativeProtocolDecoder will  
  40.                  // call me again until I return false. So just  
  41.                  // return true until there are no more lines in the  
  42.                  // buffer.  
  43.                  return true;  
  44.              }  
  45.   
  46.              previous = current;  
  47.          }  
  48.   
  49.          // Could not find CRLF in the buffer. Reset the initial  
  50.          // position to the one we recorded above.  
  51.          in.position(start);  
  52.   
  53.          return false;  
  54.      }  
  55.  }  

 

IoBuffer继承java.nio.ByteBuffer,MINA定义这个类有两个原因:

ByteBuffer没有提供get/putString这样方便的方法。

ByteBuffer只能分配固定大小的空间,IoBuffer通过setAutoExpand,expand等方法支持写入变长数据,例如:

 

Java代码   收藏代码
  1. String greeting = messageBundle.getMessage("hello");   
  2. IoBuffer buf = IoBuffer.allocate(16);  
  3. // Turn on autoExpand (it is off by default)  
  4. buf.setAutoExpand(true);  
  5. CharsetEncoder utf8encoder = Charset.forName("UTF-8").newEncoder();  
  6. buf.putString(greeting, utf8encoder);  
 

IoBuffer重新分配了底层的ByteBuffer,因为在这个例子里数据超过了16 byte。扩展的时候,ByteBuffer容量(capacity)增倍,limit则指向写入内容的最后一个位置。

 

List1代码展示的有关断包的逻辑是找到了下\r\n,即认为上一个包已经全部接收到。这是一中常见的断包逻辑,但maoyidao更喜欢使用指定包长度的方法,逻辑更清晰,代码更简单。结合http://maoyidao.iteye.com/blog/1636923 中序列化时加入的验证码,decode代码应该是这样的:

 

 

Java代码   收藏代码
  1. public class MaoyidaoDecoder  
  2.         extends CumulativeProtocolDecoder {  
  3.     protected boolean doDecode(  
  4.             IoSession session, IoBuffer in, ProtocolDecoderOutput out)  
  5.             throws Exception   
  6.     {  
  7.          CodedInputStream cis = CodedInputStream.newInstance(getBytes(in, 10));  
  8.         int pos1 = in.position();  
  9.         int pos2 = in.limit();  
  10.           
  11.         int flag1 = cis.readRawVarint32();  
  12.         int flag2 = cis.readRawVarint32();  
  13.         if(flag1 != 3 || flag2 != 7){  
  14.             // 校验码不对,丢弃这个包  
  15.             in.position(pos2);  
  16.             return true;  
  17.         }else{  
  18.             // 校验码无问题,重设postion,读下面的内容  
  19.             in.position(pos1 + 2);  
  20.         }  
  21.           
  22.         int contentLength = CodedInputStream.newInstance(getBytes(in, 5)).readRawVarint32();  
  23.         int contentLength0 = contentLength + CodedOutputStream.computeRawVarint32Size(contentLength);  
  24.           
  25.         // 是否有足够的数据  
  26.         if(in.remaining() >= contentLength0){              
  27.             try {  
  28.                 Maoyidao.MaoyidaoPacket.Builder builder = Maoyidao.MaoyidaoPacket.newBuilder();  
  29.                 CodedInputStream.newInstance(getBytes(in, protocolLength)).readMessage(builder,   
  30.                     ExtensionRegistryLite.getEmptyRegistry());                
  31.                 out.write(builder.build());  
  32.                 in.position(in.position() + protocolLength);  
  33.                 return true;  
  34.             } catch (Exception e) {  
  35.                   
  36.             }             
  37.         }  
  38.         // 没有足够的数据,返回false,IoBuffer退回到最初的位置  
  39.         else {  
  40.             in.position(pos1);  
  41.             return false;  
  42.         }  
  43.     }  
  44. }  

通过这个decodefilter,向上层的outputstream流中写入了rpc对象protobuf序列化后的字符流,这样后续处理只需根据protobuf对象,即可。

 

本系列(一)(二)2篇文章介绍了基于protobuf/MINA构建JAVA RPC的主要代码逻辑。

 

 本文系maoyidao原创,转载请引用原链接:

http://maoyidao.iteye.com/blog/1637193

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值