gRPC开发指南

Proto3 定义

syntax = "proto3"; package users.v1; option go_package = "gen/users/v1"; // 消息定义 message User { uint32 id = 1; string name = 2; string email = 3; bool active = 4; repeated string roles = 5; } message GetUserRequest { uint32 id = 1; } message ListUsersRequest { uint32 page = 1; uint32 limit = 2; string filter = 3; } message ListUsersResponse { repeated User users = 1; } // 服务定义 service UserService { rpc GetUser(GetUserRequest) returns (User); rpc ListUsers(ListUsersRequest) returns (ListUsersResponse); rpc CreateUser(User) returns (User); // 服务端流 rpc WatchUsers(ListUsersRequest) returns (stream User); // 客户端流 rpc BulkCreate(stream User) returns (ListUsersResponse); // 双向流 rpc Chat(stream Message) returns (stream Message); }

代码生成

# 安装 protoc brew install protobuf # macOS apt install protobuf-compiler # Ubuntu # Go go install google.golang.org/protobuf/cmd/protoc-gen-go@latest go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest protoc --go_out=. --go-grpc_out=. proto/users.proto # Node.js npm install @grpc/grpc-js @grpc/proto-loader # 或使用 grpc-tools npx grpc_tools_node_protoc --js_out=. --grpc_out=. proto/users.proto

gRPC vs REST 对比

特性gRPCREST
协议HTTP/2HTTP/1.1+
序列化Protobuf(二进制)JSON (text)
流式✓ 内置有限(SSE)
类型安全✓ 模式强制可选
浏览器支持需要代理✓ 原生