【Protocol Buffers教程】

本教程介绍了如何下载和安装ProtocolBuffers编译器,包括配置环境变量、执行测试以确保安装成功。接着讲解了如何安装golang的protobuf插件,并通过示例展示了如何生成Go语言代码。最后,给出了一个简单的gRPC服务代码测试案例,演示了protobuf在gRPC中的应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

下载安装Protocol Buffers编译器

下载地址

// An highlighted block
https://github.com/protocolbuffers/protobuf;

安装配置

解压缩
在这里插入图片描述
设置环境变量
在这里插入图片描述

测试

在命令行输入:protoc.exeprotoc
生成以下代码代表配置成功

Usage: protoc [OPTION] PROTO_FILES
Parse PROTO_FILES and generate output based on the options given:
  -IPATH, --proto_path=PATH   Specify the directory in which to search for
                              imports.  May be specified multiple times;
                              directories will be searched in order.  If not
                              given, the current working directory is used.
                              If not found in any of the these directories,
                              the --descriptor_set_in descriptors will be
                              checked for required proto file.
  --version                   Show version info and exit.
  -h, --help                  Show this text and exit.
  --encode=MESSAGE_TYPE       Read a text-format message of the given type
                              from standard input and write it in binary
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --deterministic_output      When using --encode, ensure map fields are
                              deterministically ordered. Note that this order
                              is not canonical, and changes across builds or
                              releases of protoc.
  --decode=MESSAGE_TYPE       Read a binary message of the given type from
                              standard input and write it in text format
                              to standard output.  The message type must
                              be defined in PROTO_FILES or their imports.
  --decode_raw                Read an arbitrary protocol message from
                              standard input and write the raw tag/value
                              pairs in text format to standard output.  No
                              PROTO_FILES should be given when using this
                              flag.
  --descriptor_set_in=FILES   Specifies a delimited list of FILES
                              each containing a FileDescriptorSet (a
                              protocol buffer defined in descriptor.proto).
                              The FileDescriptor for each of the PROTO_FILES
                              provided will be loaded from these
                              FileDescriptorSets. If a FileDescriptor
                              appears multiple times, the first occurrence
                              will be used.
  -oFILE,                     Writes a FileDescriptorSet (a protocol buffer,
    --descriptor_set_out=FILE defined in descriptor.proto) containing all of
                              the input files to FILE.
  --include_imports           When using --descriptor_set_out, also include
                              all dependencies of the input files in the
                              set, so that the set is self-contained.
  --include_source_info       When using --descriptor_set_out, do not strip
                              SourceCodeInfo from the FileDescriptorProto.
                              This results in vastly larger descriptors that
                              include information about the original
                              location of each decl in the source file as
                              well as surrounding comments.
  --dependency_out=FILE       Write a dependency output file in the format
                              expected by make. This writes the transitive
                              set of input file paths to FILE
  --error_format=FORMAT       Set the format in which to print errors.
                              FORMAT may be 'gcc' (the default) or 'msvs'
                              (Microsoft Visual Studio format).
  --fatal_warnings            Make warnings be fatal (similar to -Werr in
                              gcc). This flag will make protoc return
                              with a non-zero exit code if any warnings
                              are generated.
  --print_free_field_numbers  Print the free field numbers of the messages
                              defined in the given proto files. Groups share
                              the same field number space with the parent
                              message. Extension ranges are counted as
                              occupied fields numbers.
  --plugin=EXECUTABLE         Specifies a plugin executable to use.
                              Normally, protoc searches the PATH for
                              plugins, but you may specify additional
                              executables not in the path using this flag.
                              Additionally, EXECUTABLE may be of the form
                              NAME=PATH, in which case the given plugin name
                              is mapped to the given executable even if
                              the executable's own name differs.
  --cpp_out=OUT_DIR           Generate C++ header and source.
  --csharp_out=OUT_DIR        Generate C# source file.
  --java_out=OUT_DIR          Generate Java source file.
  --js_out=OUT_DIR            Generate JavaScript source.
  --kotlin_out=OUT_DIR        Generate Kotlin file.
  --objc_out=OUT_DIR          Generate Objective-C header and source.
  --php_out=OUT_DIR           Generate PHP source file.
  --python_out=OUT_DIR        Generate Python source file.
  --ruby_out=OUT_DIR          Generate Ruby source file.
  @<filename>                 Read options and filenames from file. If a
                              relative file path is specified, the file
                              will be searched in the working directory.
                              The --proto_path option will not affect how
                              this argument file is searched. Content of
                              the file will be expanded in the position of
                              @<filename> as in the argument list. Note
                              that shell expansion is not applied to the
                              content of the file (i.e., you cannot use
                              quotes, wildcards, escapes, commands, etc.).
                              Each line corresponds to a single argument,
                              even if it contains spaces.

安装protobuf插件

安装后会在 GOPATH 目录下生成可执行文件,protobuf的编译器插件 protoc-gen-go ,执行 protoc 命令会自动调用这个插件

// #golang 插件
go get -u github.com/golang/protobuf/protoc-gen-go ;

应该是使用下面这个命令,上面那个失效了

// #golang 插件 
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest ;

生成的插件
在这里插入图片描述

生成go文件

// 指定的当前proto语法的版本,有2和3
syntax = "proto3";
//option go_package = "path;name"; ath 表示生成的go文件的存放地址,会自动生成目录的
// name 表示生成的go文件所属的包名,可以不写,会自动生成
option go_package="../service";
// 指定等会文件生成出来的package
package service;
message User {
string username = 1;
int32 age = 2; }

写完之后在命令行进到profile文件夹执行下面命令

# 编译user.proto之后输出到service文件夹 
protoc --go_out=../service user.proto

在这里插入图片描述

代码测试

package main
import (
	"fmt"
	"goGRPC/service"
	"google.golang.org/protobuf/proto"
)
func main() {
	user := &service.User{
		Username: "mszlu",
		Age:      20,
	}
	//转换为protobuf 二进制
	marshal, err := proto.Marshal(user)
	if err != nil {
		panic(err)
	}
	fmt.Println(marshal)
	newUser := &service.User{}
	//解析二进制文件
	err = proto.Unmarshal(marshal, newUser)
	if err != nil {
		panic(err)
	}
	fmt.Println(newUser.String())
}

运行结果

[10 5 109 115 122 108 117 16 20]
username:"mszlu"  age:20

gRPC示例

来源:https://github.com/google/protobuf/releases protocolbuffer(以下简称PB)是google 的一种数据交换的格式,它独立于语言,独立于平台。google 提供了多种语言的实现,如:java、c#、c++、javascript、go 、python、ruby和php等,每一种实现都包含了相应语言的编译器以及库文件。由于它是一种二进制的格式,比使用 xml 进行数据交换快许多。可以把它用于分布式应用之间的数据通信或者异构环境下的数据交换。作为一种效率和兼容性都很优秀的二进制数据传输格式,可以用于诸如网络传输、配置文件、数据存储等诸多领域。 本资源包含: protobuf-all-3.6.0.tar.gz 8.25 MB protobuf-all-3.6.0.zip 4.25 MB protobuf-cpp-3.6.0.tar.gz 5.18 MB protobuf-cpp-3.6.0.zip 4.57 MB protobuf-csharp-3.6.0.tar.gz 5.66 MB protobuf-csharp-3.6.0.zip 4.7 MB protobuf-java-3.6.0.tar.gz 5.86 MB protobuf-java-3.6.0.zip 4.4 MB protobuf-js-3.6.0.tar.gz 5.43 MB protobuf-js-3.6.0.zip 4.59 MB protobuf-objectivec-3.6.0.tar.gz 5.69 MB protobuf-objectivec-3.6.0.zip 4.6 MB protobuf-php-3.6.0.tar.gz 5.64 MB protobuf-php-3.6.0.zip 4.53 MB protobuf-python-3.6.0.tar.gz 5.57 MB protobuf-python-3.6.0.zip 4.52 MB protobuf-ruby-3.6.0.tar.gz 5.5 MB protobuf-ruby-3.6.0.zip 1.46 MB protoc-3.6.0-linux-aarch_64.zip 1.31 MB protoc-3.6.0-linux-x86_32.zip 1.36 MB protoc-3.6.0-linux-x86_64.zip 2.44 MB protoc-3.6.0-osx-x86_32.zip 2.39 MB protoc-3.6.0-osx-x86_64.zip 984 KB protoc-3.6.0-win32.zip Source code (zip) Source code (tar.gz)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值