书店示例
go-zero 官方示例:HTTP API 网关委托给后端 gRPC 服务,使用 MySQL 持久化数据。
客户端 → bookstore-api (HTTP) → bookstore-rpc (gRPC) → MySQLgit clone https://github.com/zeromicro/go-zero.gitcd go-zero/example/bookstore| 服务 | 端口 | 说明 |
|---|---|---|
api/ | 8888 | HTTP 网关 |
rpc/ | 8080 | gRPC 书籍服务 |
启动 RPC
Section titled “启动 RPC”cd rpcgo run bookstore.go -f etc/bookstore.yaml启动 API
Section titled “启动 API”cd apigo run bookstore.go -f etc/bookstore-api.yaml# 添加书籍curl -X POST http://localhost:8888/add \ -H "Content-Type: application/json" \ -d '{"book":"The Go Programming Language","price":42}'
# 查询库存curl "http://localhost:8888/check?book=The+Go+Programming+Language"- API 网关路由到 RPC 后端
- goctl 从 MySQL DDL 生成 model
- ServiceContext 注入 RPC 客户端