RocketMQ的编解码技术细节

开发 前端
RocketMQ序列化、反序列化有两种方式:一种是将数据通过FastJSON将数据转化成JSON字符串,然后转化成byte[]数组进行编解码。另一种方式是RocketMQ定义了一套自己的编解码,将每个字段分别进行编解码。编码不论采用那种方式,都最终都编码为byte[]。

 [[405364]]

本文转载自微信公众号「漫漫技术路」,作者刘莅。转载本文请联系漫漫技术路公众号。

从上一篇文章中,我们了解的RocketMQ不同组件之间,数据是如何通过网络传输的,总结以下几点

  • RocketMQ的网络传输模块,在remoting子模块下,入口可以参考RemotingNettyServer和RemotingNettyClient两个类。
  • RocketMQ是依靠Netty,与各个组件进行数据传输。
  • RocketMQ序列化、反序列化有两种方式:一种是将数据通过FastJSON将数据转化成JSON字符串,然后转化成byte[]数组进行编解码。另一种方式是RocketMQ定义了一套自己的编解码,将每个字段分别进行编解码。编码不论采用那种方式,都最终都编码为byte[]。

今天,我们分析RocketMQ的编解码细节。在本篇文章中,可以学到:

  • RocketMQ网络协议。
  • RocketMQ在传输数据时,内存的分配。
  • RocketMQ编解码细节。

编码流程

首先,我们编码器org.apache.rocketmq.remoting.netty.NettyEncoder入手

  1. @ChannelHandler.Sharable 
  2. public class NettyEncoder extends MessageToByteEncoder<RemotingCommand> { 
  3.     private static final InternalLogger log = InternalLoggerFactory.getLogger(RemotingHelper.ROCKETMQ_REMOTING); 
  4.  
  5.     @Override 
  6.     public void encode(ChannelHandlerContext ctx, RemotingCommand remotingCommand, ByteBuf out
  7.         throws Exception { 
  8.         try { 
  9.             ByteBuffer header = remotingCommand.encodeHeader(); 
  10.             out.writeBytes(header); 
  11.             byte[] body = remotingCommand.getBody(); 
  12.             if (body != null) { 
  13.                 out.writeBytes(body); 
  14.             } 
  15.         } catch (Exception e) { 
  16.             log.error("encode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e); 
  17.             if (remotingCommand != null) { 
  18.                 log.error(remotingCommand.toString()); 
  19.             } 
  20.             RemotingUtil.closeChannel(ctx.channel()); 
  21.         } 
  22.     } 

从上面的代码,是RocketMQ将RemotingCommand对象编码成ByteBuf的唯一入口。

我们可以看到,先将header部分编码成ByteBuf,然后将body部分追加到ByteBuf里。

body部分编码很容易理解,那么header部分是怎么编码的呢?

  1. public ByteBuffer encodeHeader() { 
  2.     return encodeHeader(this.body != null ? this.body.length : 0); 
  3.  
  4. public ByteBuffer encodeHeader(final int bodyLength) { 
  5.     // 1> header length size 
  6.     int length = 4; 
  7.  
  8.     // 2> header data length 
  9.     byte[] headerData; 
  10.     headerData = this.headerEncode(); 
  11.  
  12.     length += headerData.length; 
  13.  
  14.     // 3> body data length 
  15.     length += bodyLength; 
  16.  
  17.     ByteBuffer result = ByteBuffer.allocate(4 + length - bodyLength); 
  18.  
  19.     // length 
  20.     result.putInt(length); 
  21.  
  22.     // header length 
  23.     result.put(markProtocolType(headerData.length, serializeTypeCurrentRPC)); 
  24.  
  25.     // header data 
  26.     result.put(headerData); 
  27.  
  28.     result.flip(); 
  29.  
  30.     return result; 

我们一步一步看,逻辑如下

  • 定义变量length,其初始值是4,经过几步操作,其值是4+header.length+body.length。
  • 调用headerEnocde()方法编码header部分。
  • 创建ByteBuffer并申请4+length-body.length大小的内存,其实就是4+4+header.length大小的内存。
  • 将数据写入ByteBuffer,完成header部分的编码。

我们画一张图来表示当前内存都存的什么数据。

我们可以很清楚的看到,每部分数据,分别存储在ButyBuf的什么位置,这里需要特别强调的是,byte[4]部分存储的什么,通过源码,进一步分析。

  1. result.put(markProtocolType(headerData.length, serializeTypeCurrentRPC)); 
  2.   
  3. public static byte[] markProtocolType(int source, SerializeType type) { 
  4.     byte[] result = new byte[4]; 
  5.   
  6.     result[0] = type.getCode(); 
  7.     result[1] = (byte) ((source >> 16) & 0xFF); 
  8.     result[2] = (byte) ((source >> 8) & 0xFF); 
  9.     result[3] = (byte) (source & 0xFF); 
  10.     return result; 
  11.   
  12. public enum SerializeType { 
  13.     JSON((byte) 0), 
  14.     ROCKETMQ((byte) 1); 

markProtocolType方法,第一个参数source表示header部分的长度,第二个参数type是编码类型的枚举,返回值是byte[]。

那么markProtocolType方法是做什么的呢?我们将type字段传入JSON和ROCKETMQ这两个枚举值,分别看一下,返回的是什么。

返回值共四个字节,只有第一个字节不同,第四个字节是header部分的长度,前文已经提到过,RocketMQ对header部分,可以采用两种编解码方式。

对!!没错,第一个字节就是标识编解码类型的。

解码流程

接下来我们来看解码,解码与编码稍有不同,解码器继承Netty提供的LengthFieldBasedFrameDecoder解码器,我们来看org.apache.rocketmq.remoting.netty.NettyDecoder的源码。

  1. public class NettyDecoder extends LengthFieldBasedFrameDecoder { 
  2.     private static final InternalLogger log = InternalLoggerFactory.getLogger(RemotingHelper.ROCKETMQ_REMOTING); 
  3.  
  4.     private static final int FRAME_MAX_LENGTH = 
  5.         Integer.parseInt(System.getProperty("com.rocketmq.remoting.frameMaxLength""16777216")); 
  6.  
  7.     public NettyDecoder() { 
  8.         super(FRAME_MAX_LENGTH, 0, 4, 0, 4); 
  9.     } 
  10.  
  11.     @Override 
  12.     public Object decode(ChannelHandlerContext ctx, ByteBuf in) throws Exception { 
  13.         ByteBuf frame = null
  14.         try { 
  15.             frame = (ByteBuf) super.decode(ctx, in); 
  16.             if (null == frame) { 
  17.                 return null
  18.             } 
  19.  
  20.             ByteBuffer byteBuffer = frame.nioBuffer(); 
  21.  
  22.             return RemotingCommand.decode(byteBuffer); 
  23.         } catch (Exception e) { 
  24.             log.error("decode exception, " + RemotingHelper.parseChannelRemoteAddr(ctx.channel()), e); 
  25.             RemotingUtil.closeChannel(ctx.channel()); 
  26.         } finally { 
  27.             if (null != frame) { 
  28.                 frame.release(); 
  29.             } 
  30.         } 
  31.  
  32.         return null
  33.     } 

其步骤如下:

  • 调用LengthFieldBasedFrameDecoder的decode方法,初次解码。
  • 调用RemotingCommand.decode()方法,完成对header、body部分的解码,并转化为RemotingCommand对象。

为什么要经过两次解码?

熟悉LengthFieldBasedFrameDecoder解码器的朋友都知道,LengthFieldBasedFrameDecoder解码器是Netty提供的一种非常灵活的解码器。

它在RocketMQ的NettyDecoder类中是这样被构造的。

  1. public NettyDecoder() { 
  2.     super(FRAME_MAX_LENGTH, 0, 4, 0, 4); 

LengthFieldBasedFrameDecoder我在这里不详细解释,按上面的构造方法,意思是跳过开头前4个字节。

构造出来LengthFieldBasedFrameDecoder后对RocketMQ协议进行初次解码,解码结果如下:

我们可以看到,把前四个字节,也就是把存储length字段的那部分内存截去了,只剩byte[]+header+body部分。

我们再来看RemotingCommand的解码逻辑

  1. public static RemotingCommand decode(final ByteBuffer byteBuffer) { 
  2.     int length = byteBuffer.limit(); 
  3.     int oriHeaderLen = byteBuffer.getInt(); 
  4.     int headerLength = getHeaderLength(oriHeaderLen); 
  5.  
  6.     byte[] headerData = new byte[headerLength]; 
  7.     byteBuffer.get(headerData); 
  8.  
  9.     RemotingCommand cmd = headerDecode(headerData, getProtocolType(oriHeaderLen)); 
  10.  
  11.     int bodyLength = length - 4 - headerLength; 
  12.     byte[] bodyData = null
  13.     if (bodyLength > 0) { 
  14.         bodyData = new byte[bodyLength]; 
  15.         byteBuffer.get(bodyData); 
  16.     } 
  17.     cmd.body = bodyData; 
  18.  
  19.     return cmd; 
  20.  
  21. private static RemotingCommand headerDecode(byte[] headerData, SerializeType type) { 
  22.     switch (type) { 
  23.         case JSON: 
  24.             RemotingCommand resultJson = RemotingSerializable.decode(headerData, RemotingCommand.class); 
  25.             resultJson.setSerializeTypeCurrentRPC(type); 
  26.             return resultJson; 
  27.         case ROCKETMQ: 
  28.             RemotingCommand resultRMQ = RocketMQSerializable.rocketMQProtocolDecode(headerData); 
  29.             resultRMQ.setSerializeTypeCurrentRPC(type); 
  30.             return resultRMQ; 
  31.         default
  32.             break; 
  33.     } 
  34.     return null

只剩byte[4]+header+body三个部分,解码逻辑便很清晰。可以分为以下几个步骤

  • 求出数据的长度、header的长度。
  • 根据编码类型,解码。比如通过JSON方式编码,则通过JSON方式解码。
  • 算出body的长度,解码body。
  • 将最终解码生成的RemotingCommand对象,发送给pipeline的下一个handler处理。

 

 

责任编辑:武晓燕 来源: 漫漫技术路
相关推荐

2015-04-13 10:12:08

Windows容器技术Nano Server

2017-11-10 08:35:06

存储FCoE网络

2019-05-13 08:51:53

总监技术CTO

2014-05-29 09:34:25

2019-05-06 10:51:49

总监技术场景

2020-04-03 09:05:43

麻将 AI Suphx神经网络

2023-05-08 07:20:22

Doris分析型数据库

2022-06-29 13:59:40

家居应用鸿蒙

2013-06-26 09:42:25

技术服务器内存虚拟化

2022-09-05 08:12:28

Google二进制Protobuf

2020-12-21 06:58:12

Web安全编解码工具

2018-07-17 09:34:15

Service Mes技术Kubernetes

2015-07-27 09:44:38

Amazon EC2云平台CoreOS容器

2022-04-28 07:59:11

Polkitpkexec漏洞

2009-12-02 11:03:29

AMD

2020-09-21 05:58:40

深度学习算法目标检测

2016-03-31 15:11:47

2018-04-20 14:37:43

互联网技术细节

2021-03-16 15:49:30

架构运维技术

2011-07-20 16:26:42

CA云计算VCE
点赞
收藏

51CTO技术栈公众号