Protocol Buffers- a little walk
Protocol buffers are a method of serializing data, It is useful in developing microservices to communicate with each other over a network or for storing data. The other formats like JSON, BSON, YAML and XML are also used for serializing data.
Official definition
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.
Protocol Buffer message. You need to define a .proto file for protobuf message.
syntax = "proto3";package com.protobuf.package;import "common_proto.proto";
import "google/protobuf/descriptor.proto";option java_package = "com.protobuf.package";extend google.protobuf.EnumValueOptions {
string indicator_payment_type_value_option = 100;
}message payload {
string uuid_id = 1;
int64 amount = 2;
bool feePayed = 3;
PAYMENT_TYPE = 4;}
enum PAYMENT_TYPE {
PAYMENT_TYPE_UNKNOWN = 0;
PAYMENT_TYPE_CREDIT_CARD = 1;
PAYMENT_TYPE_DEBIT_CARD = 2;}
package: It’s a optional and to prevent name clashes between protocol message types
java_package: In Java, the package is used as the Java package, unless you explicitly provide an option java_package in your .proto file.
Default values:
Protocol Buffer uses the default values for all properties.
int, for example, it will default to 0
Strings will default to empty strings, booleans to false and For enums, the default value is the first defined enum value, which must be 0
Once a message is parsed there is no way to find out whether a field was explicitly set to the default value or just not set at all.
Default values are not sent for serialization. Instead, the receiving end assumes that if a field isn’t present, then it should use the default value. This
saves space on the wire by not sending common values.
It's helpful for an old client that was built before the field existed. So that those clients can’t send the default value on the pub-sub event msg since they don’t know about that field.
Code generation
Gradle dependency
implementation 'com.google.protobuf:protobuf-java:3.15.0'
Protobuf supports several different programming languages. For each programming language, you can find instructions and maven dependency (here)
Command
$ protoc --java_out=${OUTPUT_DIR} path/to/your/proto/file
I recommend everyone check out the official documentation.