Protobuf是谷歌推出的一款平臺無關的序列化協議,相比傳統的序列化方式,Protobuf體積更小,更靈活,能有效提高傳輸效率,減少資料傳輸程序中占用的帶寬,簡單來說,Protobuf有以下特點:
語言無關、平臺無關,Protobuf支持Java、C++、Python等多種語言,多個平臺
高效,比 XML 更小(3 ~ 10倍)、更快(20 ~ 100倍)、更為簡單
擴展性、兼容性好,你可以更新資料結構,而不影響和破壞原有的舊程式
本文以Animal物體類為例,感受protobuf的特點;
public class Animal implements Serializable {
private Long id;
private String name;
private List<String> actions;
/**省略get、set方法**/
}
1.使用Protobuf
創建AnimalProto.proto,定義的資料型別如下:
package com.keduw.protobuf;
message Animal{
//id
required int64 id = 1;
//name
optional string name = 2;
//actions
repeated string actions = 3;
}
Protobuf定義了它自己的語法規則,package定義我們最后生成Java代碼所屬的包,required表示該欄位是必填的,optional表示該欄位是可選的,而repeated則標明該欄位是可連續的,對應到Java中則表示一個集合,通過定義欄位的順序方便Protobuf對欄位的反序列化,具體對應的資料型別可以參考如下:

撰寫好AnimalProto.proto,可以通過官網提供的protoc.exe生成對應的Java代碼(如果找不到可在文章末尾下載),
2.序列化和反序列化
前面通過工具生成的代碼(AnimalProto)已經幫我們封裝好了序列化和反序列化的方法,我們只需要呼叫對應方法即可,
引入Protobuf的依賴
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.4.1</version>
</dependency>
序列化:
/**
* 呼叫物件構造好的Builder,完成屬性賦值和序列化操作
* @return
*/
public static byte[] protobufSerializer(){
AnimalProto.Animal.Builder builder = AnimalProto.Animal.newBuilder();
builder.setId(1L);
builder.setName("小豬");
List<String> actions = new ArrayList<>();
actions.add("eat");
actions.add("run");
builder.addAllActions(actions);
return builder.build().toByteArray();
}
反序列化:
/**
* 通過呼叫parseFrom則完成反序列化
* @param bytes
* @return
* @throws InvalidProtocolBufferException
*/
public static Animal deserialize(byte[] bytes) throws Exception {
AnimalProto.Animal pAnimal = AnimalProto.Animal.parseFrom(bytes);
Animal animal = new Animal();
animal.setId(pAnimal.getId());
animal.setName(pAnimal.getName());
animal.setActions(pAnimal.getActionsList());
return animal;
}
測驗:
public static void main(String[] args) throws Exception {
byte[] bytes = serializer();
Animal animal = deserialize(bytes);
System.out.println(animal);
}
可以看到是能正常序列化和反序列化的,
3.性能對比
另外,我在這里還單獨對比了Java原生序列化、jackson和Protobuf序列化對同一個資料Animal操作后的資料長度,可以看到Protobuf序列化后的長度是明顯比較小,可見Protobuf的性能還是很優秀的,

至于Protobuf為什么能做到這些提高,這跟他自己定義的資料結構有關系,對于不同的資料型別采用了不同的序列化方式,對實作原理感興趣的可以自行再了解,
本文源代碼以及*.proto檔案的轉換工具:【下載】
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/242865.html
標籤:java
上一篇:Zookeeper筆記分享
下一篇:Java檔案快速copy復制
