Site icon TestingDocs.com

What are Protocol Buffers?

Overview

Protocol buffers a.k.a Protobufs are Google’s language-neutral, platform-neutral, extensible mechanism for serializing structured data. When you compare Protobuf with other serialization formats like XML and JSON, Protobufs are smaller, faster, and simpler. You can use Protobufs with many programming languages like Java,C#, C++, Python etc.

You need to define your messages in .proto file with the protocol buffers language syntax. ( proto3 or proto2 syntax)

For Example, Explicit ‘optional’ labels are disallowed in the Proto3 syntax. To define ‘optional’ fields in Proto3, simply remove the ‘optional’ label, as fields are ‘optional’ by default. Required fields are not allowed in proto3.

More information can be found at Official Protocol Buffer github repository :

https://github.com/google/protobuf

Working with protocol buffers.

Basic steps involved in working with PBs are as follows:

Step: Define message formats in a .proto file.

syntax = "proto3";

package com.testingdocs.messages;

option java_package = "com.testingdocs.proto";
option java_outer_classname = "PersonProto";

message Person {

required string name = 1;
 required int32 id = 2;
 optional string email = 3;
 
}

 

Step: Download the compiler from here:

https://github.com/google/protobuf/releases/tag/v3.3.0

Use the protocol buffer compiler ( protoc ).

Example sample command : dots in the command denote preset directory for -I  and –java_out parameters. You can specify the source directories.

/> protoc.exe -I=. –java_out=. person.proto

Step: Use the Java PB API to read/write messages.

Protocol Buffer Maven dependency for Java:

<!-- https://mvnrepository.com/artifact/com.google.protobuf/protobuf-java -->
<dependency>
 <groupId>com.google.protobuf</groupId>
 <artifactId>protobuf-java</artifactId>
 <version>3.3.1</version>
</dependency>


 

Sample Java Program:

import java.io.FileOutputStream;

import com.testingdocs.proto.PersonProto.Person;

public class ProtoBufferExample {
 
 public static void main(String[] args) throws Exception {
 FileOutputStream output;
 Person surendra = Person.newBuilder()
 .setId(007)
 .setName("S Kumar")
 .setEmail("email@testingdocs.com")
 .build();
 output = new FileOutputStream("ProgramOutput.txt");
 surendra.writeTo(output);
 output.close();
 }

}

 

Exit mobile version