go-zero
1. 环境安装
golang 安装 | go-zero Documentation
goctl
go install github.com/zeromicro/go-zero/tools/goctl@latest
protoc
这个命令可以一键安装 protoc
,protoc-gen-go
,protoc-gen-go-grpc
goctl env check --install --verbose --force
etcd
docker run -d --name my-etcd \
-p 2379:2379 \
-p 2380:2380 \
--env ALLOW_NONE_AUTHENTICATION=yes \
bitnami/etcd:latest
2. goctl 代码生成
// 1.生成api服务(根据api文件生成)
goctl api new api
// 举例
goctl api go -api api/video.api -dir api/
// 2.生成 rpc服务(根据proto文件生成)
goctl rpc new rpc
// 举例
goctl rpc protoc user/user.proto --go_out=types --go-grpc_out=types --zrpc_out=.
3. 简单的微服务 demo
建立一下目录并且编写 protoc 文件
syntax = "proto3";
package user;
option go_package="./user";
message IdRequest {
string id = 1;
}
message UserResponse {
// 用户ID
string id = 1;
// 用户名称
string name =2;
// 用户性别
bool gender = 3;
}
service User {
rpc getUser(IdRequest) returns(UserResponse);
}
使用
gctl
生成代码
# 当前目录中
goctl rpc protoc user.proto --go_out=types --go-grpc_out=types --zrpc_out=.
# 项目根目录
goctl rpc protoc user/user.proto --go_out=user/rpc/types --go-grpc_out=user/rpc/types --zrpc_out=user/rpc
在 logic 目录下面的对应文件中编写业务逻辑
首先查看响应格式,然后编写逻辑代码
func (l *GetUserLogic) GetUser(in *user.IdRequest) (*user.UserResponse, error) {
// todo: add your logic here and delete this line
return &user.UserResponse{
Id: "1",
Name: "Sakura",
Gender: true,
}, nil
}
在 Apifox 里面测试接口
创建 video 微服务,并且编写
video.api
goctl api go -api api/video.api -dir api/
video.api
type (
VideoReq {
Id string `path:"id""`
}
VideoRes {
Id string `json:"id"`
Name string `json:"name"`
}
)
service video {
@handler getVideo
get /api/videos/:id (VideoReq) returns (VideoRes)
}
添加 userRpc 配置
import (
"github.com/zeromicro/go-zero/rest"
"github.com/zeromicro/go-zero/zrpc"
)
type Config struct {
rest.RestConf
// 因为要在 video 微服务里调用user的apc服务
UserRpc zrpc.RpcClientConf
}
完善服务依赖
type ServiceContext struct {
Config config.Config
UserRpc userclient.User
}
func NewServiceContext(c config.Config) *ServiceContext {
return &ServiceContext{
Config: c,
UserRpc: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),
}
}
在 video.yaml 配置文件中添加 rpc 地址
Name: video
Host: 0.0.0.0
Port: 8888
# 添加的是 Etcd 的地址
UserRpc:
Etcd:
Hosts:
- 192.168.74.128:2379
Key: user.rpc
编写 getvideo 的逻辑
func (l *GetVideoLogic) GetVideo(req *types.VideoReq) (resp *types.VideoRes, err error) {
// todo: add your logic here and delete this line
user, err := l.svcCtx.UserRpc.GetUser(l.ctx, &user.IdRequest{
Id: "1",
})
if err != nil {
log.Fatal("err:", err)
}
return &types.VideoRes{
Id: req.Id,
Name: user.Name,
}, nil
}
运行 user.go 和 video.go
go run user\rpc\user.go -f user\rpc\etc\user.yaml
go run video\api\video.go -f video\api\etc\video.yaml
4. api 语法
评论区