GRPC: Protocol Buffers 3 语法与使用探讨

引言
Protocol Buffers(简称Protobuf)是一种语言中立、平台中立、可扩展的序列化数据结构的方式。它由Google开发,是一种类似于XML和JSON的数据交换格式,但具有更高的效率和灵活性。在本文中,我们将详细探讨Protocol Buffers 3的语法和使用方法。

1. 什么是Protocol Buffers?
Protocol Buffers是一种用于定义结构化数据的语言。它允许你定义数据结构,然后自动生成用于读写这些结构化数据的代码。与XML和JSON相比,Protobuf更加紧凑和高效,特别适合用于需要高性能和小数据量的场景,如网络通信和数据存储。
2. 安装和设置
在使用Protocol Buffers之前,需要安装Protocol Buffers编译器protoc,以及相应语言的Protobuf库。以下是安装步骤:
install on apple mac
bash
# 安装Protocol Buffers编译器brew install protobuf
install by winget on windows
powershell
winget install protobuf --verbose Found protobuf [Google.Protobuf] Version 27.1This application is licensed to you by its owner.Microsoft is not responsible for, nor does it grant any licenses to, third-party packages.Downloading https://github.com/protocolbuffers/protobuf/releases/download/v27.1/protoc-27.1-win64.zip ██████████████████████████████ 3.08 MB / 3.08 MBSuccessfully verified installer hashExtracting archive...Successfully extracted archiveStarting package install...Command line alias added: "protoc"Successfully installedprotoc --versionlibprotoc 27.1
install by python
bash
# 安装Protobuf Python库pip install protobuf
3. Protocol Buffers语法
一个Protocol Buffers文件以.proto为扩展名。以下是一个简单的.proto文件示例:
protobuf
syntax = "proto3";message Person { string name = 1; int32 id = 2; string email = 3;}
3.1 基本语法
syntax = "proto3";:指定语法版本为proto3。
message:用于定义一个消息类型。
字段类型:如string、int32。
字段标识符:每个字段都有一个唯一的标识符,如1、2、3。
3.2 字段类型
Protocol Buffers支持多种基本类型:
数值类型:int32、int64、uint32、uint64、sint32、sint64、fixed32、fixed64、sfixed32、sfixed64。
浮点数类型:float、double。
布尔类型:bool。
字符串类型:string。
字节类型:bytes。
3.3 枚举类型
枚举用于定义一组命名常量。
protobuf
enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2;}
4. 使用Protocol Buffers
4.1 编写.proto文件
首先,我们定义一个复杂的.proto文件,包含嵌套消息和枚举:
protobuf
syntax = "proto3";message Person { string name = 1; int32 id = 2; string email = 3; repeated PhoneNumber phones = 4; message PhoneNumber { string number = 1; PhoneType type = 2; } enum PhoneType { MOBILE = 0; HOME = 1; WORK = 2; }}
4.2 编译.proto文件
使用protoc编译器生成对应语言的代码:
bash
protoc --python_out=. person.proto
生成的代码示例:
python
# -*- coding: utf-8 -*-# Generated by the protocol buffer compiler. DO NOT EDIT!# NO CHECKED-IN PROTOBUF GENCODE# source: person.proto# Protobuf Python Version: 5.27.1"""Generated protocol buffer code."""from google.protobuf import descriptor as _descriptorfrom google.protobuf import descriptor_pool as _descriptor_poolfrom google.protobuf import runtime_version as _runtime_versionfrom google.protobuf import symbol_database as _symbol_databasefrom google.protobuf.internal import builder as _builder_runtime_version.ValidateProtobufRuntimeVersion( _runtime_version.Domain.PUBLIC, 5, 27, 1, '', 'person.proto')# @@protoc_insertion_point(imports)_sym_db = _symbol_database.Default()DESCRIPTOR = _descriptor_pool.Default().AddSerializedFile(b'\x0cperson.proto\"\xc3\x01\x06Person\x12\x0c\x04name\x18\x01 \x01(\t\x12\x02id\x18\x02 \x01(\x05\x12\r\x05\x65mail\x18\x03 \x01(\t\x12#\x06phones\x18\x04 \x03(\x0b\x32\x13.Person.PhoneNumber\x1a>\x0bPhoneNumber\x12\x0e\x06number\x18\x01 \x01(\t\x12\x1f\x04type\x18\x02 \x01(\x0e\x32\x11.Person.PhoneType\"+\tPhoneType\x12\x06MOBILE\x10\x00\x12\x08\x04HOME\x10\x01\x12\x08\x04WORK\x10\x02\x62\x06proto3')_globals = globals()_builder.BuildMessageAndEnumDescriptors(DESCRIPTOR, _globals)_builder.BuildTopDescriptorsAndMessages(DESCRIPTOR, 'person_pb2', _globals)if not _descriptor._USE_C_DESCRIPTORS: DESCRIPTOR._loaded_options = None _globals['_PERSON']._serialized_start=17 _globals['_PERSON']._serialized_end=212 _globals['_PERSON_PHONENUMBER']._serialized_start=105 _globals['_PERSON_PHONENUMBER']._serialized_end=167 _globals['_PERSON_PHONETYPE']._serialized_start=169 _globals['_PERSON_PHONETYPE']._serialized_end=212# @@protoc_insertion_point(module_scope)
4.3 使用生成的代码
生成的Python代码可以用于序列化和反序列化数据。
python
import person_pb2# 创建一个Person对象person = person_pb2.Person()person.id = 1234person.name = "John Doe"person.email = "johndoe@example.com"# 添加电话号码phone = person.phones.add()phone.number = "123-456-7890"phone.type = person_pb2.Person.MOBILE# 序列化为二进制数据data = person.SerializeToString()# 反序列化person2 = person_pb2.Person()person2.ParseFromString(data)print(person2)
5. Protocol Buffers的优势
高效性:Protobuf的数据格式比XML和JSON更紧凑,解析速度更快。
可扩展性:可以在不破坏现有数据的情况下,添加新的字段。
多语言支持:支持多种编程语言,如C++、Java、Python等。
结论
Protocol Buffers 3是一种强大且高效的数据序列化工具,适用于多种应用场景。在这里我们介绍了Protocol Buffers 3的基本语法和使用方法,希望能帮助大家更好地理解和使用Protobuf。在实际项目中,合理使用Protobuf可以显著提高数据传输和存储的效率。
到顶部