Protocol buffer Introduction (PROTOBUF)

Source: Internet
Author: User

I. Overview of the theory
0. References
entry information:
more detailed information:
For more detailed reference information, see the Protocol Buffer Language Guide, the Java API Reference, the Java Gene Rated Code guide, and the Encoding Reference.

1. What is PROTOBUF?
look at the official explanation.
?? Protocol buffers is Google ' s language-neutral, platform-neutral, extensible mechanism for serializing structured data–t Hink XML, but smaller, faster, and simpler. Define how do you want your data to be structured once and then you can use special generated source code to easily write an D read your structured data to and from a variety of data streams and using a variety of languages.
that is to say: Protobuf is a Google Open source project, which is a language-independent, platform-independent, extensible data serialization mechanism, similar to XML, but it is smaller, faster and simpler.

2. What can protobuf do?
It is obvious that it can be used for object serialization and deserialization, mainly for the definition of data storage and transmission format.
all RPC function parameters are defined using PROTOBUF, which is currently used in a large number of RPC communication protocols for Hadoop.

3. Advantages and disadvantages compared to XML
Pros: Smaller, faster (very inefficient for XML deserialization), and the tools can be used to generate code automatically.
disadvantage: Because the data is stored in binary, it is poor in readability???

Second, the API
1, the basic steps to use Protobuf are as follows:
(1) Define the format of the message (typically using the. Proto suffix)
(2) using the compiler provided by PROTOBUF, generate the class according to the. Proto file
(3) Use API to read and write messages

2, define the format of the message (general use. Proto suffix)


Package Tutorial;option java_package = "org.ljh.protobufdemo"; 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;}




Proto File Description, complete description See Https://
(1) The package is used to indicate namespaces to prevent conflicts with other items.
(2) If you specify Java_package, it is the package for the Java class to be generated next, otherwise the value defined in the package will be the package for the Java class.
(3) java_outer_classname Specifies the class name of the generated class, and if not specified, uses the file name of the. proto file as the class name.
(4) The message represents the definition of messages, and the messages can be nested or invoked between each other.
(5) The Equals sign after each field defines the tag for the field, because 1~15 uses less than one byte, so the labels are best left to a lot of fields, especially those defined with repeated.
(6) Each field must use one of the following 3 modifiers: required, optional, repeated.

3. Read the information from the standard input, build the person, and then serialize to a file

Package Org.ljh.protobufdemo;import;import;import;import;import;import;import;import Org.ljh.protobufdemo.addressbookprotos.addressbook;import Org.ljh.protobufdemo.addressbookprotos.person;public class Addperson {//This function fills-a person message based O  n user input. Static person promptforaddress (BufferedReader stdin, PrintStream stdout) throws Ioexceptio    n {person.builder person = Person.newbuilder ();    Stdout.print ("Enter person ID:");    Person.setid (Integer.valueof (Stdin.readline ()));    Stdout.print ("Enter name:");    Person.setname (Stdin.readline ());    Stdout.print ("Enter email address (blank for none):");    String email = stdin.readline ();    if (email.length () > 0) {person.setemail (email); } while (true) {Stdout.print ("Enter a phone number (or leave blank to finish): ");      String number = Stdin.readline ();      if (number.length () = = 0) {break;      } Person.PhoneNumber.Builder PhoneNumber = Person.PhoneNumber.newBuilder (). Setnumber (number);      Stdout.print ("Is this a mobile, home, or work phone?");      String type = Stdin.readline ();      if (Type.equals ("mobile")) {Phonenumber.settype (Person.PhoneType.MOBILE);      } else if (Type.equals ("Home")) {Phonenumber.settype (Person.PhoneType.HOME);      } else if (Type.equals ("work")) {Phonenumber.settype (Person.PhoneType.WORK);  } else {stdout.println ("Unknown phone type.      Using default. ");}    Person.addphone (PhoneNumber);  } return ();  }//Main function:reads the entire address book from a file,//Adds one person based on user input, then writes it  Back out to the same//file. public static void Main (string[] args) throws Exception {if (args.length! = 1) {System.Err.println ("Usage:addperson address_book_file");    System.exit (-1);    } Addressbook.builder AddressBook = Addressbook.newbuilder ();    Read the existing address book.    try {addressbook.mergefrom (new FileInputStream (Args[0]));  } catch (FileNotFoundException e) {System.out.println (Args[0] + ": File not found.    Creating a new file. ");    Add an address. Addressbook.addperson (Promptforaddress (New BufferedReader (New InputStreamReader (, S    Ystem.out));    Write The new Address book back to disk.    FileOutputStream output = new FileOutputStream (args[0]); (). WriteTo (output);  Output.close (); }}

Package Org.ljh.protobufdemo;import;import;import; Import Org.ljh.protobufdemo.addressbookprotos.addressbook;import Org.ljh.protobufdemo.AddressBookProtos.Person;  public class Listpeople {//iterates though all people in the AddressBook and prints info about them. static void Print (AddressBook addressbook) {for (Person person:addressBook.getPersonList ()) {System.out.println      ("Person ID:" + Person.getid ());      System.out.println ("Name:" + person.getname ());      if (Person.hasemail ()) {System.out.println ("e-mail address:" + person.getemail ()); } for (Person.phonenumber phoneNumber:person.getPhoneList ()) {switch (Phonenumber.gettype ()) {CAs            E MOBILE:System.out.print ("MOBILE phone #:");          Break            Case HOME:System.out.print ("Hls" + "ome phone #:");          Break Case WORK:System.ouT.print ("Work phone #:");        Break      } System.out.println (Phonenumber.getnumber ());  }}}//Main function:reads the entire address book from a file and prints all//the information inside. public static void Main (string[] args) throws Exception {if (args.length! = 1) {System.err.println ("usage:list      People address_book_file ");    System.exit (-1);    }//Read the existing address book.    AddressBook addressbook = Addressbook.parsefrom (new FileInputStream (Args[0]));  Print (AddressBook); }}

Protocol Buffer Introduction (PROTOBUF)

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.