Skip to content

unreal-jason/go-python-mix

Folders and files

NameName
Last commit message
Last commit date

Latest commit

 

History

1 Commit
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 

Repository files navigation

Go-Python gRPC 双向调用示例

这个项目展示了如何使用 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: 流式问候

快速开始

1. 安装依赖

Go 依赖

go mod tidy

Python 依赖

pip install -r requirements.txt

2. 生成 Protocol Buffers 代码

生成 Go 代码

cd proto
./generate_go.bat

生成 Python 代码

cd proto
python generate_python.py
# 或者
./generate_python.bat

3. 启动服务

启动 Go 服务端 (端口 50051)

cd go-server
go run main.go

启动 Python 服务端 (端口 50052)

cd python-server
python server.py

4. 测试客户端调用

Python 客户端调用 Go 服务

cd python-client
python client_go.py

Go 客户端调用 Python 服务

cd go-client
go run main.go

示例输出

Python 调用 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

Go 调用 Python 服务

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

技术特点

  1. 双向通信: Go 和 Python 可以互相作为服务端和客户端
  2. 流式支持: 支持服务端流式响应
  3. 类型安全: 使用 Protocol Buffers 确保类型一致性
  4. 高性能: gRPC 基于 HTTP/2 的高性能 RPC 框架
  5. 跨语言: 完美支持 Go 和 Python 之间的通信

开发提示

  • 修改 .proto 文件后需要重新生成代码
  • 确保服务端和客户端使用相同的 proto 定义
  • 可以使用 grpcurl 工具测试 gRPC 服务
  • 生产环境建议使用 TLS 加密通信

故障排除

端口冲突

确保端口 50051 和 50052 未被占用

依赖问题

  • Go: 确保安装了 protoc-gen-goprotoc-gen-go-grpc
  • Python: 确保安装了 grpcio-tools

生成代码问题

检查 Protocol Buffers 编译器版本是否匹配

About

go and python call each other by grpc

Resources

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published