Protobuf (quickStart), protobufquickstart

Source: Internet
Author: User

Protobuf (quickStart), protobufquickstart
1. Introduction

Protocol Buffers is a data description language developed by Google. It serializes data and can be used in data storage and communication protocols.

It can be understood as faster, simpler, and smaller JSON or XML. The difference is that Protocol Buffers is in binary format, while JSON and XML are in text format.

Compared with XML, Protocol Buffers has the following advantages:

1. Concise

2. small size, the message size is only 1/10 to 1/3 of XML.

3. fast resolution speed: 20-20 faster than XML ~ 100 times.

4. Use the Protocol Buffers compiler to generate data access code that is easier to use in programming.

5. For better compatibility, one principle of Protocol Buffers design is to be able to support backward or upward compatibility.

 

Compare the number of bytes serialized into different data description languages:

 

The speed comparison of serialization and deserialization during data transmission using different data description languages in the network:

 

 

 

2. Syntax Rules of the proto File

 

1. Use the message keyword to define a message and specify the message name (take a meaningful name)

2. Specify the field type and name

3. Add field constraints

4. Define the field number (starting from 1, where 19000 ~ 19999 used as a reserved field by Protocol Buffers)

 

The most basic message

message User{    required int32 id = 1;    required string username = 2;    required string password = 3;    optional string email = 4;}

 

Field Type

Field Constraints

Required: this field must be assigned a value.

Optional indicates that the field can be null. You can use [default] to specify the default value. If no default value is specified, the default value of the field type is used.

Repeated specifies a set of fields.

One of the specified fields must be assigned a value.

 

*In a proto file, multiple message types can be defined at the same time. When code is generated, the processing method varies according to the target language of the generated code. (Java will generate one message for each message type. java file ).

Message User {required int32 id = 1; // a field between username and email must be assigned oneof login {string username = 3; string email = 4 ;} required string password = 2;} message Admin {required int32 id = 1; required string username = 2; required string password = 3 ;}

 

* The field type can be specified as another message type.

message Course{    required User user = 1;    required string cour_name = 2; }message User{    required int32 id = 1;    required string username = 2;    required string password = 3;    optional string email = 4;}

 

* Type Nesting is supported in the proto file, that is, the defined message type is only used as the field type that contains the message type.

message Course{    message User{        required int32 id = 1;        required string username = 2;        required string password = 3;        optional string email = 4;    }    required User user = 1;    required string cour_name = 2; }

 

* Use the extensions keyword to reserve the field number of the Message Type and use the extend keyword to continue the definition.

Message User {// 30 ~ 100 private. extensions 30 to 100} extend User {required int32 id = 1; required string username = 2; required string password = 3; optional string email = 4 ;}

 

* You can use the import keyword to import other proto files.

* You can use option java_package to set the name of the java class to be generated.

* You can use option java_outer_classname to set the Class Name of the generated java class.

import "other.proto"option java_package = "com.zht.protobuf";option java_outer_classname = "UserModel";message User{    required int32 id = 1;    required string username = 2;    required string password = 3;    optional string email = 4;}

  

3. Use of protobuf

 

1. Prepare the environment

 

Download protobuf Toolkit: https://github.com/google/protobuf/releases for the corresponding operating environment on github

Windows user selection:Protoc-3.5.1-win32.zip

Decompress the package and configure the environment variable PATH so that it can directly search for protoc.exe in the context.

 

2. Compile the. proto File

 

E: \ proto \ user. proto

The content is as follows:

syntax = "proto2";option java_package = "com.zht.protobuf";option java_outer_classname = "UserModel";message User{    required int32 id = 1;    required string username = 2;    required string password = 3;    optional string email = 4;}

 

3.use the protoc.exe command to generate an object

 

Protoc.exe-I [directory of the proto file] -- java_out [directory of the JAVA class] [absolute path of the proto file]

 

 

 

 

4. Put the entity into the project to construct and assign values to the entity

 

Put entities into the project:

 

Construct and assign values:

Public class Main {public static void main (String [] args) throws InvalidProtocolBufferException {// get the constructor and assign a value to UserModel. user. builder builder = UserModel. user. newBuilder (); builder. setId (1); builder. setUsername ("zhuanght"); builder. setPassword ("123456"); builder. setEmail ("aiuzht119@163.com"); // get the entity UserModel. user user = builder. build (); System. out. println ("source data: \ r" + user. toString (); System. out. println ("serialized:" + Arrays. toString (user. toByteArray (); // simulate receiving Byte [] and deserialize it into the User object byte [] data = user. toByteArray (); User u = User. parseFrom (data); System. out. println ("\ r resolution: \ r" + u. toString ());}}

 

Print result:

Source data: id: 1 username: "zhuanght" password: "123456" email: "aiuzht119@163.com" after serialization: [8, 1, 18, 8,122,104,117, 97,110,103,104,116, 26, 6, 49, 50, 51, 52, 53, 54, 34, 17, 97,105,117,122,104,116, 49, 49, 57, 64, 49, 54, 51, 46, 99,111,109] resolution: id: 1 username: "zhuanght" password: "123456" email: "aiuzht119@163.com"

  

5. Get the serialized byte array for transmission in the Network

 

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.