How Java uses Protobuf serialization and deserialization
Protobuf is a data serialization framework developed by Google, also known as Protocol Buffers. It can serialize structured data into binary format and restore binary data to structured data through deserialization. Due to its efficient serialization and deserialization performance, as well as its compact data storage format, Protobuf is widely used in distributed systems.
To use Protobuf in Java, the following steps need to be followed:
1. Define message structure: Use Protobuf language to define the structure of a message, which is similar to a data model used to describe the fields and types of data.
2. Compile. proto files: Use the Protobuf compiler to compile. proto files into Java classes, thereby using these classes in Java code.
3. Use the Protobuf API: Serialize and deserialize messages using compiled Java classes.
Here are some commonly used Protobuf methods and corresponding Java code examples:
1. Encoder method
//Create a Protobuf encoder
com.google.protobuf.CodedOutputStream output = CodedOutputStream.newInstance(outputStream);
//Serializing a message
message.writeTo(output);
//Turn off encoder
output.flush();
output.close();
2. Decoder method
//Create a Protobuf decoder
com.google.protobuf.CodedInputStream input = CodedInputStream.newInstance(inputStream);
//Read a message from the input stream
MyMessage message = MyMessage.parseFrom(input);
//Turn off decoder
input.checkLastTagWas(0);
3. Serialization and Deserialization Methods
//Serializing messages as byte arrays
byte[] data = message.toByteArray();
//Deserialize byte arrays into messages
MyMessage message = MyMessage.parseFrom(data);
4. Maven Dependency
In order to use Protobuf in Java projects, corresponding Maven dependencies need to be added:
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>3.10.0</version>
</dependency>
The above is the basic method and sample code for serialization and deserialization using Protobuf. By defining message structures, compiling. proto files, and using the Protobuf API, it is easy to serialize and deserialize data. Also, remember to add Protobuf's Maven dependency to the Java project's dependencies.