Introduction to Google ProtoBuf

1. Background

Some time ago, I learned that there are companies using technologies such as gRPC, Pulsar, Nacos, SkyWalking, OpenTelemetry, Prometheus, Envoy, Grafana, Sonar, PowerJob, and Apollo, which are also based on the Java route. I am very ashamed. I hardly understand any of these. Since 2013, Playing with Android, playing with Python, playing with Linux, and playing with products, we don’t pay enough attention to new Java technologies, and now we must follow up. . .

gRPC uses ProtoBuf for serialization/deserialization, so today we first learn how to do ProtoBuf serialization.

2. Introduction to ProtoBuf

ProtoBuf is a language-independent, efficient , and extensible object serialization method.

There are many serialization methods, and ProtoBuf is by far the most efficient serialization method.

Proto is divided into two versions: Proto2 and Proto3. The following example uses the Proto3 version.

The specific syntax will not be explained in detail. You can refer to the official documentation.

https://developers.google.cn/protocol-buffers/docs/proto3?hl=zh_cn

3. Use of ProtoBuf

1. Create a .proto file and define the data structure

Install the ProtoBuf Support plug-in in IDEA to support syntax prompts when writing .proto files.

Add protobuf-java dependency to the project


<dependency>
  <groupId>com.google.protobuf</groupId>
  <artifactId>protobuf-java</artifactId>
  <version>3.18.0-rc-2</version>
</dependency>

Configure the protobuf-maven-plugin plug-in, which is used to generate corresponding class code from .proto files. Note: The installation of this plug-in was not successful, and the compilation was later performed through the command line.

Create the proto Source directory under /src/main and create the User.proto file as follows.

2. Compile the .proto file and generate the class

Install protobuf under mac, download protobuf3.18


./configure --prefix=/usr/local/protobuf
sudo -i
make && make install

Configuration Environment

Execute the compilation command to generate the UserEntity class

protoc --java_out=. User.proto

3. Call the class to implement serialization and deserialization

Supongo que te gusta

Origin blog.csdn.net/2301_76787421/article/details/133544393
Recomendado
Clasificación