侧边栏壁纸
博主头像
帥甲博主等级

行动起来,活在当下

  • 累计撰写 27 篇文章
  • 累计创建 11 个标签
  • 累计收到 1 条评论

目 录CONTENT

文章目录

GRPC笔记

帥甲
2024-04-03 / 0 评论 / 0 点赞 / 45 阅读 / 2754 字

ProtoC使用

ProtoC介绍

Protocol Buffers是Google开发的一种数据序列化协议,类似于JSON或XML,但更小、更快、更简单。protoc是Protocol Buffers的编译器,用于将.proto文件编译成可在应用程序中使用的代码,包括Java、C++、Python、golang等。这使得跨语言通信变得更加容易,因为不同的应用程序可以使用相同的数据结构和接口定义进行通信。

go环境插件安装


# 用来生成proto文件中message生成对应的结构体和方法
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
# 用来生成proto文件中service生成对应的方法和grpc相关代码
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest

proto文件编写

// proto版本
syntax = "proto3";
// 包名称
package pb;
// 生成go代码的包名称
option go_package = ".;proto";

// The request message containing the user's name.
message HelloRequest {
    string name = 1;
}

// The response message containing the greetings
message HelloReply {
    string message = 1;
}

// The greeter service definition.
service Greeter {
    // Sends a greeting
    rpc SayHello (HelloRequest) returns (HelloReply) {}
}

proto文件编译

protoc --go_opt=paths=source_relative --go_out=. --go-grpc_opt=paths=source_relative --go-grpc_out=. ./example.proto
  • --go_opt=paths=source_relative //设置pb.go文件路径为相对路径

  • --go_out=. //设置pb.go文件路径

  • --go-grpc_opt=paths=source_relative //设置grpc.pb.go文件路径为相对路径

  • --go-grpc_out=. //设置grpc.pb.go文件路径

  • ./example.proto //proto文件相对路径

0

评论区