本文是对 使用go-zero快速构建微服务[1]的亲手实践
编写API Gateway代码
mkdir bookstore && cd bookstore
go mod init bookstore
mkdir api && goctl api -o api/bookstore.api
syntax = "v1"
info(
title: "xx使用go-zero"
desc: "xx用来上手go-zero"
author: "xxxx"
email: "xxxx@gmail.com"
)
type (
addReq struct {
book string `form:"book"`
price int64 `form:"price"`
}
addResp struct {
ok bool `json:"ok"`
}
)
type (
checkReq struct {
book string `form:"book"`
}
checkResp struct {
found bool `json:"found"`
price int64 `json:"price"`
}
)
service bookstore-api {
@handler AddHandler
get /add (addReq) returns (addResp)
@handler CheckHandler
get /check (checkReq) returns (checkResp)
}
cd api && goctl api go -api bookstore.api -dir .
api
├── bookstore.api // api定义
├── bookstore.go // main入口定义
├── etc
│ └── bookstore-api.yaml // 配置文件
└── internal
├── config
│ └── config.go // 定义配置
├── handler
│ ├── addhandler.go // 实现addHandler
│ ├── checkhandler.go // 实现checkHandler
│ └── routes.go // 定义路由处理
├── logic
│ ├── addlogic.go // 实现AddLogic
│ └── checklogic.go // 实现CheckLogic
├── svc
│ └── servicecontext.go // 定义ServiceContext
└── types
└── types.go // 定义请求、返回结构体
go run bookstore.go -f etc/bookstore-api.yaml
启动API Gateway服务,默认侦听在8888端口
因为默认生成的api/etc/bookstore-api.yml为:
Name: bookstore-api
Host: 0.0.0.0
Port: 8888
按提示下载,再次运行:
{"@timestamp":"2023-02-16T16:31:09.658+08:00","caller":"stat/usage.go:61","content":"CPU: 0m, MEMORY: Alloc=2.5Mi, TotalAlloc=2.5Mi, Sys=14.5Mi, NumGC=0","level":"stat"}
{"@timestamp":"2023-02-16T16:31:09.662+08:00","caller":"load/sheddingstat.go:61","content":"(api) shedding_stat [1m], cpu: 0, total: 0, pass: 0, drop: 0","level":"stat"}
{"@timestamp":"2023-02-16T16:31:15.044+08:00","caller":"stat/metrics.go:210","content":"(bookstore-api) - qps: 0.0/s,

本文详细介绍了如何使用go-zero框架快速构建微服务,包括编写APIGateway,实现RPC服务,以及数据库操作和依赖管理。开发者通过实例展示了如何创建API接口,调用RPC服务,并集成数据库操作和缓存机制。
最低0.47元/天 解锁文章
1047

被折叠的 条评论
为什么被折叠?



