What are Protocol Buffers?
From the Protobuf documentation:
- Protocol buffers are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data – think XML, but smaller, faster, and simpler.
- You define how you want your data to be structured once, then you can use special generated source code to easily write and read your structured data to and from a variety of data streams and using a variety of languages.
Getting started
- Read the overview from here
- From here pick your favorite language.
- Follow the guide for your favorite language.
Example with Java
- Go to the Protocol Buffer Basics: Java page.
- The example, based from here, is a very simple address book application that can read and write people’s contact details to and from a file. Each person in the address book has a name, an ID, an email address, and a contact phone number.
- We need to start with a .proto file (e.g. addressbook.proto)
- Generate the classes you’ll need to read and write your messages using the protocol buffer compiler
protoc
-
If you haven’t installed the compiler, download the package and
- Unzip the file you downloaded and set it in a location where you want to install protoc
- Go to the folder and install the C++ Protocol Buffer runtime and the Protocol Buffer compiler (protoc) executing the following:
$ ./configure $ make $ make check $ sudo make install $ sudo ldconfig # refresh shared library cache.
-
Once protoc is installed, run:
protoc -I=$SRC_DIR --java_out=$DST_DIR $SRC_DIR/addressbook.proto
where
SRC_DIR
is the source directory where your application’s source code lives and theDST_DIR
is the destination directory, where you want the generated code to go.for example:
protoc -I=/Users/username/dev/playing-with-protobuf/src/main/proto --java_out=/Users/username/dev/playing-with-protobuf/src/main/java /Users/username/dev/playing-with-protobuf/src/main/proto/addressbook.proto
-
- A new class named
AddressBookProtos
should be generated under thecom.play.protobuf.gen
package. - Play around using the new class that was created, example here
- Next, play more! Write personal details to your address book file using the com.play.protobuf.AddPerson class.
- Run it passing as param the path of your
ADDRESS_BOOK_FILE
- Run it passing as param the path of your
- Next, play more! Read the personal details from your address book file using the com.play.protobuf.ListPeople class.
- Run it passing as param the path of your
ADDRESS_BOOK_FILE
- Run it passing as param the path of your
- Check out the Java API reference to see what else you can do with Protocol Buffers.
- To learn and know more about Protocol Buffers check the API Reference
All the code for this example is located here