目标

  • 基于 gPRC 官方的 helloworld 案例
  • 使用 Rust 实现此案例的服务端和客户端
  • 使用 Go 实现此案例的服务端和客户端
  • 使用 Rust 实现的客户端分别调用 Rust 和 Go 实现的服务端
  • 使用 Go 实现的客户端分别调用 Rust 和 Go 实现的服务端

环境准备

项目结构

├── helloworld_go ➡️ go 实现
│   ├── client ➡️ go 实现的客户端
│   │   └── main.go
│   ├── go.mod
│   ├── go.sum
│   ├── pb  ➡️ 根据 proto 生成的 go 代码
│   │   ├── helloworld.pb.go
│   │   └── helloworld_grpc.pb.go
│   └── server ➡️ go 实现的服务端
│       └── main.go
├── helloworld_rs  ➡️ rust 实现
│   ├── Cargo.lock
│   ├── Cargo.toml
│   ├── build.rs ➡️ 在构建时,自动根据 proto 生成 rust 代码
│   └── src
│       ├── client.rs  ➡️ rust 实现的客户端
│       ├── pb ➡️ 根据 proto 生成的 rust 代码
│       │   ├── helloworld.rs
│       │   └── mod.rs
│       └── server.rs  ➡️ rust 实现的服务端
└── proto ➡️  proto 代码
    └── helloworld.proto

helloworld.proto

本专题对 helloworld.proto 作了有关 package 的修改:

  • 删除 java 相关的包定义
  • 增加 go 需要的包定义
syntax = "proto3";
option go_package = "helloworld_go/pb"; // go 语言的包名
package helloworld; // rust 会根据此定义生成 mod
// 定义 Greeter 服务
service Greeter {
  // 发送问候
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// 发送问候的请求,包含用户的名字
message HelloRequest {
  string name = 1;
}
// 问候的响应
message HelloReply {
  string message = 1;
}

开始学习

创建项目目录,比如 grpc_helloworld_go_rust

mkdir grpc_helloworld_go_rust && cd grpc_helloworld_go_rust

创建rust项目,比如helloworld_rs

cargo new helloworld_rs

创建go项目,比如 helloworld_go

创建 proto 目录,并写入 helloworld.proto

mkdir proto && \
cat > proto/helloworld.proto << EOF
syntax = "proto3";
option go_package = "helloworld_go/pb"; // go 语言的包名
package helloworld; // rust 会根据此定义生成 mod
// 定义 Greeter 服务
service Greeter {
  // 发送问候
  rpc SayHello (HelloRequest) returns (HelloReply) {}
}
// 发送问候的请求,包含用户的名字
message HelloRequest {
  string name = 1;
}
// 问候的响应
message HelloReply {
  string message = 1;
}
EOF