序列化数据的要求
- 效率 时间空间
- 多语言相互操作
- 使用方便
ProtoBuffer 使用:
- Designing objects
Person: Id Name Age Email Phone(s)
- Describing objects
Person: required int32 id required string name optional string email repeated string phone
- Compiling the description
package tutorial; option java_package = "com.example.tutorial"; option java_outer_classname = "AddressBookProtos"; message Person { required string name = 1; required int32 id = 2; optional string email = 3; enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; } message PhoneNumber { required string number = 1; optional PhoneType type = 2 [default = HOME]; } repeated PhoneNumber phone = 4; } message AddressBook { repeated Person person = 1; }
protoc --java_out=$DST_DIR addressbook.proto
- Obtaining the generated source-code
- Importing objects into your project
- Instantiating objects
Person john = Person.newBuilder() .setId(12345) .setName .setEmail .addPhone(Person.PhoneNumber.newBuilder() .setNumber("+351 999 999 999") .setType(Person.PhoneType.HOME) .build()) .build();
- Using objects
// Writing data to a file FileOutputStream aOutput = new FileOutputStream("theFilename") Person aPerson = Person.newBuilder.set().... //instance a Person aPerson.writeTo(aOutput); aOutput.close(); // Reading data from a file Person aPerson = Person.parseFrom(new FileInputStream("theFilename")) // Do something with the received Person
ProtoBuffer 重点在
- Efficiency (space and time) 效率 (空间和时间)
- Language interoperability 多语言互操作性
- Usability 方便使用
其它解决方案
- Avro (http://avro.apache.org/)
- Thrift (http://thrift.apache.org/)
- Kryo (https://github.com/EsotericSoftware/kryo)
时间: 2024-10-10 07:24:24