【協議】MessagePack, Protocol Buffers和Thrift序列化框架原理和比較說明

非常好的說明文章,轉自:http://jimmee.iteye.com/blog/2042420


第1部分  messagepack說明

1.1messagepack的消息編碼說明

爲什麼messagepackjson序列化使用的字節流更少, 可通過圖1-1、圖1-2有個直觀的感覺。

 

 

1- 1 messagepackjson的格式對比1



 

1- 2 messagepackjson的格式對比2

messagepack的具體的消息格式如圖1-3所示,messagepack的數據類型主要分類兩類:固定長度類型和可變長度類型。



 

1- 3 messagepack的消息格式

messagepack的具體類型信息表示如圖1-4所示。

 

 

1- 4 messagepack的類型信息

1.2 messagepack的序列化和反序列化方式

現在msgpack能支持基本的數據類型,支持listmap, 還支持自定義的數據類型。例子1, 序列化和反序列化一個javabean, 只要加上@MessagePackMessage的註解。

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1.   
  2. @MessagePackMessage   
  3. public class Person {  
  4.   
  5. public int id;  
  6.   
  7. public String name;  
  8.   
  9. public double height;  
  10.   
  11. public Person() {  
  12. }  
@MessagePackMessage 
public class Person {

public int id;

public String name;

public double height;

public Person() {
}

 

 

 

序列化直接調用MessagePackpack方法;反序列化則調用對應的unpack方法。這兩個方法,都支持傳遞序列化和反序列化的數據類型。

1.3 與json的序列化性能對比

如下所示,通過100條數據的序列化和反序列化進行對比。

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. List msgs = new ArrayList();  
  2. for (int i = 0; i < 100; i++) {  
  3. Map msg = new HashMap();  
  4. msg.put(Const.FID, i);  
  5. msg.put(Const.SUBJECT, "subject" + i);  
  6. msg.put(Const.LABEL0, 1);  
  7. msg.put(Const.FROM, "[email protected]");  
  8. msg.put(Const.TO, "[email protected]");  
  9. msg.put(Const.MODIFIED_DATE, new Date().getTime());  
  10. msg.put(Const.RECEIVED_DATE, new Date().getTime());  
  11. msg.put(Const.SENT_DATE, new Date().getTime());  
  12. msgs.add(msg);  
  13.     }  
Listmsgs = new ArrayList(); for (int i = 0; i < 100; i++) { Map msg = new HashMap(); msg.put(Const.FID, i); msg.put(Const.SUBJECT, "subject" + i); msg.put(Const.LABEL0, 1); msg.put(Const.FROM, "[email protected]"); msg.put(Const.TO, "[email protected]"); msg.put(Const.MODIFIED_DATE, new Date().getTime()); msg.put(Const.RECEIVED_DATE, new Date().getTime()); msg.put(Const.SENT_DATE, new Date().getTime()); msgs.add(msg); }

 

 

比較結果如表1-1所示。

1- 1 messagepackjson的性能對比

框架

字節大小(byte

序列化時間(ns

反序列化時間(ns

messagepack

12793

2313335

529458

json

17181

 1338371

1776519

 

可以看出,messagepack的序列化字節數比json小將近30%;序列化時間messagepack差不多是json的兩倍;反序列化時間,messagepack只需要json30%的時間。

但是,值得注意的是,雖然messagepack的反序列化時間比較少,但是要真正轉換爲前端需要的類型參數格式,還需要額外的一些時間。

第2部分 protocol buffers

2.1 protocol buffers的消息編碼說明

Protocol Buffers支持的數據類型如下圖所示:



  

2- 1 protocol buffers支持的數據類型。

首先對Varint進行說明。Varint 是一種緊湊的表示數字的方法。它用一個或多個字節來示一個數字,值越小的數字使用越少的字節數。這能減少用來表示數字的字節數。

比如對於 int32 類型的數字,一般需要 個 byte 來表示。但是採用 Varint,對於很小的 int32 類型的數字,則可以用 個 byte 來表示。當然,採用 Varint 表示法,大的數字則需要 個 byte 來表示。從統計的角度來說,一般不會所有的消息中的數字都是大數,因此大多數情況下,採用 Varint 後,可以用更少的字節數來表示數字信息。

Varint 中的每個 byte 的最高位 bit 有特殊的含義,如果該位爲 1,表示後續的 byte 也是該數字的一部分,如果該位爲 0,則結束。其他的 個 bit 都用來表示數字。因此小於 128 的數字都可以用一個 byte 表示。大於 128 的數字,比如 300,會用兩個字節來表示:1010 1100 0000 0010

2-2說明了 Google Protocol Buffer 如何解析兩個 bytes。注意到最終計算前將兩個 byte 的位置相互交換過一次,這是因爲 Google Protocol Buffer 字節序採用 little-endian 的方式。



  

2- 2 protocol buffers解析兩個字節

消息經過序列化後會成爲一個二進制數據流,該流中的數據爲一系列的 Key-Value 對,如圖2-3所示。



  

2- 3 protocol buffers的消息流

採用這種 Key-Pair 結構無需使用分隔符來分割不同的 Field。對於可選的 Field,如果消息中不存在該 field,那麼在最終的 Message Buffer 中就沒有該 field,這些特性都有助於節約消息本身的大小。

假設我們生成如下的一個消息Message

 Message.id = 5

 Message.info = 「hello」

則最終的 Message Buffer 中有兩個 Key-Value 對,一個對應消息中的 id;另一個對應 info

Key 用來標識具體的 field,在解包的時候,Protocol Buffer 根據 Key 就可以知道相應的 Value 應該對應於消息中的哪一個 field

Key 的定義如下:

 (field_number << 3) | wire_type 

可以看到 Key 由兩部分組成。第一部分是 field_number。第二部分爲 wire_type。表示 Value 的傳輸類型。

wire type如表2-1所示。

2- 1 wire type說明

Type 

Meaning 

Used For 

Varint 

int32, int64, uint32, uint64, sint32, sint64, bool, enum 

64-bit 

fixed64, sfixed64, double 

Length-delimited 

string, bytes, embedded messages, packed repeated fields 

Start group 

Groups (deprecated) 

End group 

Groups (deprecated) 

32-bit 

fixed32, sfixed32, float 

 

在計算機內,一個負數一般會被表示爲一個很大的整數,因爲計算機定義負數的符號位爲數字的最高位。如果採用 Varint 表示一個負數,那麼一定需要 個 byte。爲此 Google Protocol Buffer 定義了 sint32sint64 類型,採用 zigzag 編碼。

Zigzag 編碼用無符號數來表示有符號數字,正數和負數交錯,如圖2-3所示。使用 zigzag 編碼,絕對值小的數字,無論正負都可以採用較少的 byte 來表示,充分利用了 Varint 這種技術。


  

2- 4 ZigZag編碼

2.2 protocol buffers的序列化和反序列化

步驟:

創建消息的定義文件.proto

使用protoc工具將proto文件轉換爲相應語言的源碼;

使用類庫支持的序列化和反序列化方法進行操作。

 

以同樣的數據的操作爲例:

1. 定義proto文件messages.ptoto

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. message MessageMeta {  
  2.   required int32 id = 1;  
  3.   required string subject = 2;    
  4. optional int32 lablel0 = 3;  
  5. required string from = 4;  
  6. required string to = 5;  
  7. optional int64 modifiedDate = 6;  
  8. optional int64 receivedDate = 7;  
  9. optional int64 sentDate = 8;  
  10. }  
message MessageMeta {
  required int32 id = 1;
  required string subject = 2;  
optional int32 lablel0 = 3;
required string from = 4;
required string to = 5;
optional int64 modifiedDate = 6;
optional int64 receivedDate = 7;
optional int64 sentDate = 8;
}

 

 

 

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. message MessageMetas {  
  2. repeated MessageMeta msg = 1;  
  3. }  
message MessageMetas {
repeated MessageMeta msg = 1;
}

 

 

2. message.proto文件轉換爲java語言的源碼

例如, 執行命令:protoc -I=src --java_out=out src/messages.proto產生Messagesjava文件。

3. 執行序列化和反序列化

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. MessageMetas.Builder msgsBuilder = MessageMetas.newBuilder();  
  2. for (int i = 0; i < 100; i++) {  
  3. MessageMeta.Builder msgBuilder = MessageMeta.newBuilder();  
  4. msgBuilder.setId(i);  
  5. msgBuilder.setSubject("subject" + i);  
  6. msgBuilder.setLablel0(1);  
  7. msgBuilder.setFrom("[email protected]");  
  8. msgBuilder.setTo("[email protected]");  
  9. msgBuilder.setModifiedDate(new Date().getTime());  
  10. msgBuilder.setReceivedDate(new Date().getTime());  
  11. msgBuilder.setSentDate(new Date().getTime());  
  12. msgsBuilder.addMsg(msgBuilder.build());  
  13. }  
  14. MessageMetas msgs = msgsBuilder.build();  
MessageMetas.Builder msgsBuilder = MessageMetas.newBuilder();
for (int i = 0; i < 100; i++) {
MessageMeta.Builder msgBuilder = MessageMeta.newBuilder();
msgBuilder.setId(i);
msgBuilder.setSubject("subject" + i);
msgBuilder.setLablel0(1);
msgBuilder.setFrom("[email protected]");
msgBuilder.setTo("[email protected]");
msgBuilder.setModifiedDate(new Date().getTime());
msgBuilder.setReceivedDate(new Date().getTime());
msgBuilder.setSentDate(new Date().getTime());
msgsBuilder.addMsg(msgBuilder.build());
}
MessageMetas msgs = msgsBuilder.build();

 

 

之後調用相應的writeTo方法進行序列化, 調用parseFrom進行反序列化。

2.3 與json等的性能對比

2- 2 性能對比表格

框架

字節大小(byte

序列化時間(ns

反序列化時間(ns

messagepack

12793

2313335

529458

protocol buffers

6590

941790

408571

json

17181

 1338371

1776519

 

可以看出,protocol buffers在字節流,序列化時間和反序列化時間方面都明顯較優(即空間和時間上都比較好)。

第3部分 thrift

thrift的架構如圖3-1所示。圖3-1顯示了創建serverclientstack。最上面的是IDL,然後生成ClientProcessor。紅色的是發送的數據。protocoltransport Thrift運行庫的一部分。通過Thrift 你只需要關心服務的定義,而不需要關心protocoltransport

Thrift支持 text 和 binary protocolsbinary protocols要比text protocols,但是有時候 text protocols比較有用(例如:調試的時候)。支持的協議有:

TBinaryProtocol 直接的二進制格式

TCompactProtocol 效率和高壓縮編碼數據

TDenseProtocoal  和TCompactProtocol相似,但是省略了meta信息,從哪裏發送的,增加了receiver。還在實驗中,java實現還不可用。

TJSONProtocoal使用JSON

TSImpleJSONProtocoal 只寫的protocol使用JSON。適合被腳本語言轉化

TDebugProtocoal使用人類可讀的text 格式 幫助調試



  

3- 1 thrift架構圖

上面的protocol 說明了傳送的是什麼樣的數據Thrift transports 則說明了怎樣傳送這些數據。支持的transport

TSocket 使用 blocking socket I/O

TFramedTransport 以幀的形式發送,每幀前面是一個長度。要求服務器來non-blocking server

TFileTransport 寫到文件

TMemoryTransport 使用內存 I/O java實現中在內部使用了ByteArrayOutputStream

TZlibTransport 壓縮 使用zlibjava實現中還不可用

最後,thrift 提供了servers

TSimpleServer 單線程server,使用標準的blocking IO用於測試

TThreadPoolServer多線程server 使用標準的blocking IO

TNonblockingServer  多線程 server使用 non-blocking IO java實現中使用了NIO channels),TFramedTransport必須使用在這個服務器。

一個server只允許定義一個接口服務。這樣的話多個接口需要多個server。這樣會帶來資源的浪費。通常可以通過定義一個組合服務來解決。

3.1 thrift的消息編碼說明

1. 支持的數據類型

所有編程語言中都可用的關鍵類型。

bool 布爾值,真或假

byte 有符號字節

i16  16位有符號整數

i32  32位有符號整數

i64  64位有符號整數

double 64位浮點數

string 與編碼無關的文本或二進制字符串

可基於基本類型定義結構體,例如:

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. struct Example {  
  2. 1:i32 number=10,  
  3. 2:i64 bigNumber,  
  4. 3:double decimals,  
  5. 4:string name="thrifty"  
  6. }  
struct Example {
1:i32 number=10,
2:i64 bigNumber,
3:double decimals,
4:string name="thrifty"
}

 

 

支持的容器有listsetMap

若使用TCompactProtocol,傳遞的消息形式如圖3-2所示:

 

 

3- 2 thriftcompact方式的消息流

在這種方式下,對整數而言,也是採用可變長度的方式進行實現。一個字節,最高位表示是否還有數據,低7位是實際的數據,如圖3-3所示, 整數106903的編碼, 相比普通的int類型,節省一個字節。



  

3- 3 compact方式對一個整數106903進行編碼

3.2thrift的序列化和反序列化方式

步驟:

創建thrift接口定義文件;

thrift的定義文件轉換爲對應語言的源代碼;

選擇相應的protocol,進行序列化和反序列化。

仍以同樣的數據對象爲例子:

定義thrift文件messages.thrift

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. struct MessageMeta {  
  2.   1:i32 id;  
  3.   2:string subject;    
  4. 3:i32 lablel0;  
  5. 4:string from;  
  6. 5:string to;  
  7. 6:i64 modifiedDate;  
  8. 7:i64 receivedDate;  
  9. 8:i64 sentDate;  
  10. }  
  11.    
  12. struct MessageMetas {  
  13. 1:list msgs;  
  14. }  
struct MessageMeta {
  1:i32 id;
  2:string subject;  
3:i32 lablel0;
4:string from;
5:string to;
6:i64 modifiedDate;
7:i64 receivedDate;
8:i64 sentDate;
}
 
struct MessageMetas {
1:list msgs;
}

 

 

 

2. 將定義的文件轉換成相應的java源碼

執行命令:thrift -gen java messages.thrift

3. 執行序列化和反序列化

 

Java代碼   收藏代碼【協議】MessagePack, <wbr>Protocol <wbr>Buffers和Thrift序列化框架原理和比較說明
  1. MessageMetas msgs = new MessageMetas();  
  2. List msgList = new ArrayList();  
  3. for (int i = 0; i < 100; i++) {  
  4. MessageMeta msg = new MessageMeta();  
  5. msg.setId(i);  
  6. msg.setSubject("subject" + i);  
  7. msg.setLablel0(1);  
  8. msg.setFrom("[email protected]");  
  9. msg.setTo("[email protected]");  
  10. msg.setModifiedDate(new Date().getTime());  
  11. msg.setReceivedDate(new Date().getTime());  
  12. msg.setSentDate(new Date().getTime());  
  13. msgList.add(msg);  
  14. }  
  15. msgs.setMsgs(msgList);  
  16. // 序列化  
  17. ByteArrayOutputStream out = new ByteArrayOutputStream();  
  18. TTransport trans = new TIOStreamTransport(out);  
  19. TBinaryProtocol tp = new TBinaryProtocol(trans);  
  20. msgs.write(tp);  
  21.    
  22. byte [] buf = out.toByteArray();  
  23. // 反序列化  
  24. ByteArrayInputStream in = new ByteArrayInputStream(buf);  
  25. trans = new TIOStreamTransport(in);  
  26. tp = new TBinaryProtocol(trans);  
  27. MessageMetas msgs2 = new MessageMetas();  
  28. msgs2.read(tp);  
MessageMetas msgs = new MessageMetas();
List msgList = new ArrayList();
for (int i = 0; i < 100; i++) {
MessageMeta msg = new MessageMeta();
msg.setId(i);
msg.setSubject("subject" + i);
msg.setLablel0(1);
msg.setFrom("[email protected]");
msg.setTo("[email protected]");
msg.setModifiedDate(new Date().getTime());
msg.setReceivedDate(new Date().getTime());
msg.setSentDate(new Date().getTime());
msgList.add(msg);
}
msgs.setMsgs(msgList);
// 序列化
ByteArrayOutputStream out = new ByteArrayOutputStream();
TTransport trans = new TIOStreamTransport(out);
TBinaryProtocol tp = new TBinaryProtocol(trans);
msgs.write(tp);
 
byte [] buf = out.toByteArray();
// 反序列化
ByteArrayInputStream in = new ByteArrayInputStream(buf);
trans = new TIOStreamTransport(in);
tp = new TBinaryProtocol(trans);
MessageMetas msgs2 = new MessageMetas();
msgs2.read(tp);

 

 

3.3json等的性能對比

3- 1 性能對比

框架

字節大小(byte

序列化時間(ns

反序列化時間(ns

messagepack

12793

2313335

529458

protocol buffers

6590

941790

408571

thrift

6530

798696

754458

json

17181

 1338371

1776519

 

通過對比,可以發現thrift總的來說,都比較不錯。

第4部分 小結

通過對messagepackprotocol buffers以及thrift的分析,主要分析了這些框架的序列化和反序列化部分的內容。實際上messagepackthrift都還有自己的rpc調用框架。

所有的測試都是在本機上進行,基於100條元數據進行測試。可能不同數據,以及不同的規模,測試結果應該會存在差別,https://github.com/eishay/jvm-serializers/wiki/的有比較好的測試結果說明。根據自己的測試,從性能上說,messagepackprotocol buffers以及thrift都比json好(在測試時,發現messagepack序列化的時間稍微多一些)。

從編程語言上來說,messagepackprotocol buffers以及thrift,當然還包括json,都是支持跨語言的通訊的。

從接口定義的靈活性來(或者是否支持動態類型),messagepackprotocol buffers以及thrift較好,後兩者都要預先定義schema並相對固定

 

 實際工作中, 一般都採用protocol buffers或者thrift.

 

第5部分 參考資料

1. http://msgpack.org/

2. http://code.google.com/intl/zh-CN/apis/protocolbuffers/docs/overview.html

3. http://jnb.ociweb.com/jnb/jnbJun2009.html

4. http://code.google.com/p/thrift-protobuf-compare/

5. http://www.tbdata.org/archives/1307

6. https://github.com/eishay/jvm-serializers/wiki/

7. http://wiki.apache.org/thrift/

8. http://pypi.python.org/pypi/msgpack-python/