赞
踩
来自:指月小筑 https://lixueduan.com
原文:https://lixueduan.com/post/grpc/01-protobuf/
本文主要记录了 Protobuf 的基本使用。包括 编译器 protoc 、Go Plugins 安装及 .proto文件定义、编译等。
如果你对云原生技术充满好奇,想要深入了解更多相关的文章和资讯,欢迎关注微信公众号。
扫描下方二维码或搜索公众号【探索云原生】即可订阅
Protocol buffers 是一种语言无关、平台无关的可扩展机制或者说是数据交换格式,用于序列化结构化数据。与 XML、JSON 相比,Protocol buffers 序列化后的码流更小、速度更快、操作更简单。
Protocol buffers are a language-neutral, platform-neutral extensible mechanism for serializing structured data.
protoc 用于编译 protocolbuf (.proto文件) 和 protobuf 运行时。
protoc 是 C++ 写的,比较简单的安装方式是直接下载编译好的二进制文件。
release 版本下载地址如下
https://github.com/protocolbuffers/protobuf/releases
下载操作系统对应版本然后解压然后配置一下环境变量即可。
比如windows
就下载protoc-3.14.0-win64.zip
然后把解压后的xxx\protoc-3.14.0-win64\bin
配置到环境变量。
linux
则下载protoc-3.14.0-linux-x86_64.zip
解压
$ unzip protoc-3.14.0-linux-x86_64.zip -d protoc-3.14.0-linux-x86_64
新增环境变量
$ sudo vim /etc/profile
增加如下内容
#记得改成自己的路径
export PATH=$PATH:/home/lixd/17x/protoc-3.14.0-linux-x86_64/bin
使其生效
$ source /etc/profile
查看是否安装成功
$ protoc --version
libprotoc 3.14.0
出了安装 protoc 之外还需要安装各个语言对应的编译插件,我用的 Go 语言,所以还需要安装一个 Go 语言的编译插件。
go get google.golang.org/protobuf/cmd/protoc-gen-go
hello_world.proto
//声明 protobuf 版本 只有 proto3 才支持 gRPC syntax = "proto3"; // .表示生成go文件输出在当前目录,proto 表示生成go文件包名为proto option go_package = ".;proto"; // 指定当前proto文件属于helloworld包 package helloworld; // The greeting service definition. service Greeter { // Sends a greeting rpc SayHello (HelloRequest) returns (HelloReply) {} } // // The request message containing the user's name. message HelloRequest { string name = 1; } // The response message containing the greetings message HelloReply { string message = 1; }
编译命令
# Syntax: protoc [OPTION] PROTO_FILES
$ protoc --proto_path=IMPORT_PATH --go_out=OUT_DIR --go_opt=paths=source_relative path/to/file.proto
这里简单介绍一下 golang 的编译姿势:
-I
:指定 import 路径,可以指定多个参数,编译时按顺序查找,不指定时默认查找当前目录。
--java_out
等等--go_opt=paths=source_relative
就是表明生成文件输出使用相对路径。$ protoc --go_out=. hello_word.proto
编译后会生成一个hello_word.pb.go
文件。
到此为止就ok了。
可以把 protoc 的编译过程分成简单的两个步骤:
具体过程如图所示:
protoc 中原生包含了部分语言(java、php、python、ruby等等)的编译插件,但是没有 Go 语言的,所以需要额外安装一个插件。
具体原生支持见源码
https://github.com/protocolbuffers/protobuf/blob/master/src/google/protobuf/compiler/main.cc
同样的,后续讲到的 gRPC Plugins、gRPC-Gateway 也是一个个的 protoc 编译插件,将 .proto 文件编译成对应模块需要的源文件。
如果你对云原生技术充满好奇,想要深入了解更多相关的文章和资讯,欢迎关注微信公众号。
扫描下方二维码或搜索公众号【探索云原生】即可订阅
https://developers.google.com/protocol-buffers
https://github.com/protocolbuffers/protobuf
https://studygolang.com/articles/12673
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。