当前位置:网站首页>Understand the use of protobuf serialization protocol
Understand the use of protobuf serialization protocol
2022-06-21 13:54:00 【The forest wind is at ease】
Protobuf It is a platform independent serialization protocol launched by Google , Compared with the traditional serialization ,Protobuf A smaller , More flexible , Can effectively improve transmission efficiency , Reduce the bandwidth occupied during data transmission . Simply speaking ,Protobuf Has the following characteristics :
Language has nothing to do 、 Platform independent .Protobuf Support Java、C++、Python multilingual , Multiple platforms
Efficient . Than XML smaller (3 ~ 10 times )、 faster (20 ~ 100 times )、 It's simpler
Extensibility 、 Compatibility is good. . You can update the data structure , Without affecting and destroying the original old program
This article takes Animal Take entity class as an example , feel protobuf Characteristics ;
public class Animal implements Serializable {
private Long id;
private String name;
private List<String> actions;
/** Omit get、set Method **/
}
One 、 Use Protobuf
establish AnimalProto.proto, The data types defined are as follows :
package com.keduw.protobuf;
message Animal{
//id
required int64 id = 1;
//name
optional string name = 2;
//actions
repeated string actions = 3;
}
Protobuf Defines its own grammar rules .package Define what we finally generate Java The package to which the code belongs ,required Indicates that this field is required ,optional Indicates that the field is optional , and repeated Indicates that the field is continuous , Corresponding to Java Middle represents a set , It is convenient to define the order of fields Protobuf Deserialization of fields . The specific corresponding data types can be referred to as follows :
Write it well AnimalProto.proto, It can be provided through the official website protoc.exe Generate corresponding Java Code ( If you can't find it, you can download it at the end of the article ).
Two 、 Serialization and deserialization
The code previously generated by the tool (AnimalProto) The methods of serialization and deserialization have been encapsulated for us , We just need to call the corresponding method .
introduce Protobuf Dependence
<dependency>
<groupId>com.google.protobuf</groupId>
<artifactId>protobuf-java</artifactId>
<version>2.4.1</version>
</dependency>
serialize :
/** * The call object is constructed Builder, Complete attribute assignment and serialization * @return */
public static byte[] protobufSerializer(){
AnimalProto.Animal.Builder builder = AnimalProto.Animal.newBuilder();
builder.setId(1L);
builder.setName(" Piglets ");
List<String> actions = new ArrayList<>();
actions.add("eat");
actions.add("run");
builder.addAllActions(actions);
return builder.build().toByteArray();
}
Deserialization :
/** * By calling parseFrom Then deserialization is completed * @param bytes * @return * @throws InvalidProtocolBufferException */
public static Animal deserialize(byte[] bytes) throws Exception {
AnimalProto.Animal pAnimal = AnimalProto.Animal.parseFrom(bytes);
Animal animal = new Animal();
animal.setId(pAnimal.getId());
animal.setName(pAnimal.getName());
animal.setActions(pAnimal.getActionsList());
return animal;
}
test :
public static void main(String[] args) throws Exception {
byte[] bytes = serializer();
Animal animal = deserialize(bytes);
System.out.println(animal);
}
You can see that it can be serialized and deserialized normally .
3、 ... and 、 Performance comparison
in addition , I have also made a separate comparison here Java Native serialization 、jackson and Protobuf Serialization of the same data Animal Data length after operation , You can see Protobuf The length after serialization is obviously small , so Protobuf The performance of the is still excellent .
as for Protobuf Why can we achieve these improvements , On the one hand, data mapping is completed by defining field order , So you don't have to save the field name , On the other hand , This has something to do with the data structure he defines himself , Different serialization methods are used for different data types , Those who are interested in the implementation principle can understand by themselves .
The source code of this article and *.proto File conversion tools :【 download 】
边栏推荐
- Lamp architecture 6 -- MySQL master-slave replication and optimization method
- Automatic operation and maintenance 4 - variables and encryption in ansible
- Modification method of EKF extended Kalman filter for omnidirectional ground
- Design and implementation of object system in redis
- 3D slicer import label and view label
- MySQL - transaction management
- C language -- program compilation and linking
- Babbitt yuancosmos daily must read: wechat may ban a official account for the first time on the grounds of "involving secondary transactions in digital collections", and the new regulations of the pla
- Kotlin - sequence sequence
- Design interface automation test cases by hand: establish database instances and test case tables
猜你喜欢

Detailed explanation of dictionary source code in C #

MySQL - table join and join

Hands on data analysis unit 2 section 4 data visualization
![[googolu] takeout rebate system - business domain name of KFC configuration applet](/img/54/d30b9c08e46760dac8c3405716941f.jpg)
[googolu] takeout rebate system - business domain name of KFC configuration applet

【课程作业】浮点运算分析及精度改进

MySQL - built in functions

MySQL - view properties

Using the path module to prompt errors in ts+vite projects

3D slicer saves segmentation results
![[deeply understand tcapulusdb technology] tmonitor background one click installation](/img/0a/742503e96a9b51735f5fd3f598b9af.png)
[deeply understand tcapulusdb technology] tmonitor background one click installation
随机推荐
Test the interface between app and wechat applet
Must the database primary key be self incremented? What scenarios do not suggest self augmentation?
使用seaborn绘制热图
服务治理的工作内容
给网站添加SSL安全证书
Unbounded territory won the title of innovative brand of digital culture industry in 2022
Technology sharing | a clustering incremental statistical SQL requirement in MySQL
Use map set or list set to store list set
[in depth understanding of tcapulusdb technology] tcapulusdb business data backup
Solution to the problem of long waiting (ttfb) time during web page loading
scrapy_ Redis distributed crawler
map. Values() to copy list and ArrayList
Postman reports error write eproto 93988952error10000f7ssl routinesopenssl_ internalWRONG_ VERSION_ NUM
Iterm2 file transfer with remote server
Lamp architecture 5 - MySQL Cluster and master-slave structure
Map collection traversal, adding, replacing and deleting elements
618 Nuggets digital collection? Burberry and other luxury brands fight against metauniverse
Kubernetes' fast practice and core principle analysis
C language elementary level (IX) enumeration
技术分享 | MySQL中一个聚类增量统计 SQL 的需求