使用protostuff进行序列化
2019獨角獸企業重金招聘Python工程師標準>>>
使用protostuff進行序列化 博客分類: java按官方的說法,protostuff是一個序列化庫,提供了向后兼容和驗證的內置支持。
而我們用protostuff的原因,也就是他真正牛逼的地方在于,他可以把一個POJO序列化為多種格式:
- protobuf
- protostuff (native)
- graph (protostuff with support for cyclic references. See Serializing Object Graphs)
- json
- smile (binary json useable from the protostuff-json module)
- xml
- yaml (serialization only)
- kvp (binary uwsgi header)
只要一個POJO+protostuff就能轉換為這么多格式!用過protobuf的應該知道,谷歌PB官方是不支持處理POJO的,每個語言平臺都只能用protoc生成的代碼來進行序列化反序列化,而protoc生成的代碼非常復雜,是整合了序列化邏輯的一個類,這個類除了用來進行protobuf格式的序列化,無法用作其他用途了。而POJO我們都愛,所以我們選擇了使用protobuf來把POJO序列化為protobuf格式的數據。
例子
寫一個用protostuff進行protobuf格式的序列化的例子:
引入protostuff的依賴:
| <dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-core</artifactId> <version>1.3.5</version> </dependency> <dependency> <groupId>io.protostuff</groupId> <artifactId>protostuff-runtime</artifactId> <version>1.3.5</version> </dependency> |
新建一個用于序列化的POJO:
| public class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } @Override public String toString() { return "Person{" + "name='" + name + '\'' + ", age=" + age + '}'; } } |
編寫序列化和反序列化例子:
| Person p = new Person("mushan",20); LinkedBuffer buffer = LinkedBuffer.allocate(); Schema<Person> schema = RuntimeSchema.getSchema(Person.class); byte[] protobuf = ProtobufIOUtil.toByteArray(p, schema, buffer); Person person = schema.newMessage(); ProtobufIOUtil.mergeFrom(protobuf,person,schema); System.out.println(person); |
輸出:Person{name='mushan', age='20'}。說明反序列化成功。
定義字段順序
使用過protobuf的一定知道,protobuf序列化反序列化不是依賴名稱的,而是依賴字段的位置,也被成為字段的tag。默認情況下,protostuff使用字段的定義順序作為字段的tag。但是需要注意的是,這個特性不是每種JVM都支持的。sun體系的JVM都沒問題,但是比如像安卓的dalvik虛擬機,在反射的時候,獲取的字段順序就不一定是定義順序了,所以有時候我們需要手動指定字段的tag。這時我們可以使用protostuff提供的Tag注解:
| public final class Bar { @Tag(8) int baz; } |
protostuff生成的protobuf格式的數據能被protobuf自己生成的類解析么?
能。我只測試了簡單類型。對于復雜類型會不會出現不兼容還不清楚,同時對于版本的兼容性也還不太清楚。
將POJO生成proto文件
這個需要使用webbynet/protostuff-runtime-proto: Protostuff Runtime Proto Files Generator這個項目。
使用非常簡單,通過RuntimeSchema得到schema后直接就可以生成proto:
| String content = Generators.newProtoGenerator(schema).generate(); System.out.println(content); |
參考資料
- protostuff/protostuff: Java serialization library, proto compiler, code generator
- protostuff
- Protostuff詳解 - chszs的專欄 - 博客頻道 - CSDN.NET
http://mushanshitiancai.github.io/2016/09/02/java/%E4%BD%BF%E7%94%A8protostuff%E8%BF%9B%E8%A1%8C%E5%BA%8F%E5%88%97%E5%8C%96/
https://my.oschina.net/OutOfMemory/blog/800226
轉載于:https://my.oschina.net/xiaominmin/blog/1597963
總結
以上是生活随笔為你收集整理的使用protostuff进行序列化的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: 一文掌握关于Java数据结构所有知识点(
- 下一篇: 漂亮 动态效果 信息提示(jquery版