首页 > 代码库 > ProtoBuffer

ProtoBuffer

 

序列化数据的要求

  1.        效率  时间空间
  2.        多语言相互操作
  3.        使用方便

ProtoBuffer 使用:

  1. Designing objects

    Person:IdNameAgeEmailPhone(s)

      

  2. Describing objects
    Person:required int32 idrequired string nameoptional string emailrepeated string phone

     

  3. 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

     

  4. Obtaining the generated source-code
  5. Importing objects into your project

  6. 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();

     

  7. Using objects
    // Writing data to a fileFileOutputStream  aOutput  = new FileOutputStream("theFilename")Person  aPerson = Person.newBuilder.set()....   //instance  a PersonaPerson.writeTo(aOutput);aOutput.close();
    // Reading data from a filePerson aPerson = Person.parseFrom(new FileInputStream("theFilename"))// Do something with the received Person

     

ProtoBuffer 重点在

  1. Efficiency (space and time)   效率 (空间和时间)

  2. Language interoperability     多语言互操作性
  3. Usability                             方便使用

 

其它解决方案

  1. Avro (http://avro.apache.org/)

  2. Thrift (http://thrift.apache.org/)
  3. Kryo (https://github.com/EsotericSoftware/kryo)

 

ProtoBuffer