这个项目展示了如何使用 gRPC 实现 Go 和 Python 之间的相互调用。包含以下组件:
go-python-mix/
├── proto/ # Protocol Buffers 定义
│ ├── user_service.proto # 服务定义
│ ├── generate_go.bat # Go proto 生成脚本
│ ├── generate_python.py # Python proto 生成脚本
│ └── generate_python.bat # Python proto 生成批处理
├── go-server/ # Go 服务端
│ └── main.go # Go 服务实现
├── python-server/ # Python 服务端
│ └── server.py # Python 服务实现
├── python-client/ # Python 客户端
│ └── client_go.py # Python 调用 Go 服务
├── go-client/ # Go 客户端
│ └── main.go # Go 调用 Python 服务
├── go.mod # Go 模块定义
└── requirements.txt # Python 依赖
- UserService: 用户管理服务
- GetUser: 获取用户信息
- CreateUser: 创建用户
- ListUsers: 列出用户
- HelloService: 问候服务
- SayHello: 简单问候
- SayHelloStream: 流式问候
go mod tidy
pip install -r requirements.txt
cd proto
./generate_go.bat
cd proto
python generate_python.py
# 或者
./generate_python.bat
cd go-server
go run main.go
cd python-server
python server.py
cd python-client
python client_go.py
cd go-client
go run main.go
INFO:root:=== Creating users via Go server ===
INFO:root:Created user: id: "user-3"
name: "Python Client"
email: "python@client.com"
age: 25
INFO:root:=== Getting user from Go server ===
INFO:root:Got user: id: "user-3"
name: "Python Client"
email: "python@client.com"
age: 25
INFO:root:=== Saying hello to Go server ===
INFO:root:Response: Hello Python Client! This is Go server
2024/01/01 10:00:00 === Creating users via Python server ===
2024/01/01 10:00:00 Created user: id:"user-3" name:"Go Client" email:"go@client.com" age:30
2024/01/01 10:00:00 === Saying hello to Python server ===
2024/01/01 10:00:00 Response: Hello Go Client! This is Python server
- 双向通信: Go 和 Python 可以互相作为服务端和客户端
- 流式支持: 支持服务端流式响应
- 类型安全: 使用 Protocol Buffers 确保类型一致性
- 高性能: gRPC 基于 HTTP/2 的高性能 RPC 框架
- 跨语言: 完美支持 Go 和 Python 之间的通信
- 修改
.proto
文件后需要重新生成代码 - 确保服务端和客户端使用相同的 proto 定义
- 可以使用
grpcurl
工具测试 gRPC 服务 - 生产环境建议使用 TLS 加密通信
确保端口 50051 和 50052 未被占用
- Go: 确保安装了
protoc-gen-go
和protoc-gen-go-grpc
- Python: 确保安装了
grpcio-tools
检查 Protocol Buffers 编译器版本是否匹配