Introduction and examples of Google ProtocolBuffer (PB), protocolbufferpb
Introduction
- ProtocolBuffer (PB) is a lightweight and efficient storage format for structured data serialization.
- Similar to xml and json, PB is more efficient and space-saving than the former two, and saves user traffic in mobile development.
- How can PB reduce traffic? From its encoding method, PB adopts the Zigzag encoding and makes full use of the Varint technology to save space in the level-2 system.
Instance
- Step 1: Write the. proto file. Go to the official google instance and store it as addressbook. proto
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;}
- Step 2: Compile the. proto file, use the PB-related compilation tool protoc, and generate a java class
protoc -I=$SRC_DIR --cpp_out=$DST_DIR $SRC_DIR/addressbook.proto
protoc -I=. --java_out=. addressbook.proto
- Step 3: Apply the generated classes and perform serialization and deserialization operations, depending on the library protobuf-java-2.6.1.jar (and the version must be consistent with the previous protoc Version)
// Generate the object Person john = Person. newBuilder (). setId (1234 ). setName ("John Doe "). setEmail ("jdoe@example.com "). addPhone (Person. phoneNumber. newBuilder (). setNumber ("555-4321 "). setType (Person. phoneType. HOME )). build (); System. out. println (john. toString (); // serialized as a binary array byte [] johnbyte = john. toByteArray (); // deserialization (the intermediate process can be considered as a network transfer, file storage, etc.) // compare the two systems. out output try {Person john2 = Person. parseFrom (johnbyte); System. out. println (john2.toString ();} catch (InvalidProtocolBufferException e) {// TODO Auto-generated catch block e. printStackTrace ();}
Extension
- Write. proto details
- PB Encoding Algorithm
- Notes for PB-based protocol upgrade
Download
- The following addresses provide complete download of the above instance project, resources include: protobuf-2.6.1.zip source code; protoc-2.6.1-win32; protobuf-java-2.6.1.jar; A serialized deserialization instance
- Download Portal
Reference
- Http://www.ibm.com/developerworks/cn/linux/l-cn-gpb/#ibm-pcon
- Http://www.cnblogs.com/shrimps/archive/2008/11/06/1327988.html
- Http://stackoverflow.com/questions/14028293/google-protocol-buffers-vs-json-vs-xml
- Https://github.com/google/protobuf
- Https://developers.google.com/protocol-buffers/docs/downloads
- Https://developers.google.com/protocol-buffers/docs/javatutorial
- Http://repo2.maven.org/maven2/com/google/protobuf/protobuf-java/2.6.1/