protobuf
课件
安装
- 安装protobuf编译器
$ protoc --version
libprotoc 3.21.12
- 安装Go语言插件
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ protoc-gen-go --version
protoc-gen-go.exe v1.31.0
- vscode protobuf插件支持
vscode-proto3
编译
protoc prootbuf3 ---> go struct
# hello 目录内执行
$ protoc -I=. --go_out=. --go_opt=module="gitee.com/go-course/go12/skills/protobuf/hello" hello.proto
# gitee.com/go-course/go12/skills 作为module 就必须在工程根目录取执行
protoc -I=. --go_out=. --go_opt=module="gitee.com/go-course/go12/skills" protobuf/hello/hello.proto
go_package: 决定了编译后的目标文件 存放的位置:
option go_package="": 把该文件对应的go语言包 放到对应目录下去
gomodule: gitee.com/go-course/go12/skills
目录: /protobuf/hello
// (--go_out指定的目录) + (go_package里面去除module过后的部分)
// ./protobuf/hello <--- hello.pb.go
- protobuf 数据结构 --protoc-gen-go--> Go语言数据结构
- 为生成好的对象 struct, 生成 基于porotobuf 序列化和反序列化的方法
接口数据结构定义
+ message --> struct
+ enum ---> type cosnt
+ []any ---> repeated message()
+ map<string, string> ---> map[string]string
引用其他protobuf
syntax = "proto3";
package test;
option go_package="gitee.com/go-course/go12/skills/protobuf/test";
import 'protobuf/hello/hello.proto';
message Request {
// 采用工程的根目录 作为搜索的起始目录
// import 时 要采用 工程的根目录作为起始
hello.String string = 1;
}
接口定义(grpc)
需要安装grpc插件
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
protobuf 如何定义接口
// service 声明一个接口定义 ---> type HelloService interface
service HelloService {
// Hello(HelloRequest, HelloResponse)
rpc Hello(HelloRequest, HelloResponse);
}
需要指定插件的执行参数:
# gitee.com/go-course/go12/skills 作为module 就必须在工程根目录取执行
protoc -I=. --go_out=. --go_opt=module="gitee.com/go-course/go12/skills" --go-grpc_out=. --go-grpc_opt=module="gitee.com/go-course/go12/skills" protobuf/hello/hello.proto