A tour of gRPC:02 - 从 proto 生成代码

在上一部分,我们了解了 gRPC 的一些基础理论,接下来我们将尝试编写 proto 文件,并通过配套的生成 器生成 Java 和 golang 的代码。在实践的部分我将尝试构建一个笔记本销售平台,方便我们在实践中进行 学习。
从 proto 生成 golang
1. 新建项目
2. 创建 proto 文件夹
3. 添加 processor_message.proto 文件夹 并 添加一下内容:

如何定义协议信息?
使用 message 后面跟消息名称,在其消息块内,定义其所有字段,格式如下:
a. 消息名称格式应为大驼峰命名
b. 字段名格式应为小写蛇形
c. 数据类型有:string、bool、bytes、float、double、int32、int64、uint32、uint64、sint32、sint64...
d. 每个消息字段应分配一个唯一的标签,标签比字段名称更重要,因为 protobuf 将使用它来序列化消 息。标签不必是有序或者顺序的,但是对于消息的同级别字段,它们必须是唯一的。

4. 从 protocol buffer 生成 go 代码
a. 安装 protobuf: brew install protobuf
b. 通过 protoc 命令检查是否正确安装
c. 安装两个 go-libraries

根据 go 版本选择使用上面的 go get 或
【 go install github.com/golang/protobuf/protoc- gen-go@latest 】
d. 创建一个 pb 文件夹用于存储生成的代码,并执行以下命令。

如果我们每次都输入如此繁琐的命令确实令人烦恼,所以我们可以编写一个简单的 Makefile 减少重复输 入复杂的命令

运行了上面的生成代码后,我们可以在项目目录下的 pb 文件夹下看到已经生成了 processor_message.pb.go
5. 有了上面的经验,我们不妨在 process_message.proto 中添加一个 GPU 信息
a. 在添加 GPU 前,我们还需要先添加一个描述内存的类型 memory_message.proto 用于描述显 存。一个描述内存的 message 应该由 大小 和 单位两部分所组成
新建一个 memory_message.proto 增加内存的描述

b. 有了描述显存的 memory_message 我们遍可以紧接着添加 GPU 的内容了,这里我们要使 用 import 将 mermory_message 的内容进行导入(如果这里 IDE 提示无法导入,则需要设置一下 IDE 参考这个https://blog.csdn.net/z449077880/article/details/121741524)

运行 make gen 进行生成。
6. 同理,我们接下来添加描述键盘配列的 keyboard_message.proto、描述屏幕的 screen_message.proto 、描述存储的 storage_message.proto 和描述笔记本信息的 laptop_message.proto
a. keyboard_message.proto

b. screen_message.proto

c. storage_message.proto

d. laptop_message.proto

运行 make gen 生成代码,可以观察到 pb 文件夹下已经成功的生成了 golang 代码
从 proto 生成 Java
1. 新建一个 maven 项目
2. 导入以下依赖

3. 将上文.proto 文件夹拷⻉至 main 目录下的 proto 文件夹(需要创建,并右键 make as source root)
4. 运行 mvn clean comple 观察到 Java 下的 pcbook 中已经生成了代码。



版权声明: 本文为 InfoQ 作者【BUG侦探】的原创文章。
原文链接:【http://xie.infoq.cn/article/e6121b5f6cb8c67fd8570fbc4】。文章转载请联系作者。
评论