go go-zero的学习,持续中...
官网地址
https://go-zero.dev/
命令行
自动创建rpc和api服务
- 构建rpc服务
goctl rpc new user
手动创建服务
命令要在user.proto
所在的目录
goctl rpc protoc user.proto --go_out=. --go-grpc_out=. --zrpc_out=.
API创建
自动创建api
goctl api new api
手动创建api
goctl api go -api user.api -dir . -style gozero
etcd 安装
go-zero 默认配置是etcd
下载不同系统的版本
https://github.com/etcd-io/etcd/releases
解压后获得两个主要的程序 etcd.exe 和 etcdctl.exe
加入环境变量
D:\software\etcd-v3.6.4-windows-amd64\etcd-v3.6.4-windows-amd64
验证安装
etcd --version
etcd Version: 3.6.4
Git SHA: 5400cdc
Go Version: go1.23.11
Go OS/Arch: windows/amd64
运行etcd -单节点运行
.\etcd.exe ^
--name etcd01 ^
--data-dir .\data\etcd01 ^
--advertise-client-urls http://127.0.0.1:2379 ^
--listen-client-urls http://127.0.0.1:2379 ^
--listen-peer-urls http://127.0.0.1:2380 ^
--initial-advertise-peer-urls http://127.0.0.1:2380 ^
--initial-cluster etcd01=http://127.0.0.1:2380 ^
--initial-cluster-state newpause
验证是否成功
etcdctl --endpoints=http://127.0.0.1:2379 endpoint health# 期望结果http://127.0.0.1:2379 is healthy: successfully committed proposal: took = 3.4443ms
查看当前 etcd 集群中所有成员(节点)状态
etcdctl.exe member list
# 期望结果
b71f75320dc06a6c, started, etcd01, http://127.0.0.1:2380, http://127.0.0.1:2379, false
运行go-zero rpc
切换到 ·user/api·
记得加.
go run .
测试
-
使用apipost,新建grpc
-
导入proto文件
-
测试
运行go-zero api
切换到 ·user/api·
记得加.
goctl api go -api user.api -dir . -style gozero
go run .
api 调用grpc服务
1、修改api-yml配置文件
user/api/etc/user.yaml
UserRpc:Etcd:Hosts:- 127.0.0.1:2379Key: user.rpc
2、修改配置文件
user/api/internal/config/config.go
package configimport ("github.com/zeromicro/go-zero/rest""github.com/zeromicro/go-zero/zrpc"
)type Config struct {rest.RestConfUserRpc zrpc.RpcClientConf # 新增
}
3、修改svc
user/api/internal/svc/servicecontext.go
新增userclient.User
package svcimport ("github.com/zeromicro/go-zero/zrpc""go-zero-user/api/internal/config""go-zero-user/rpc/userclient"
)type ServiceContext struct {Config config.Configuserclient.User
}func NewServiceContext(c config.Config) *ServiceContext {return &ServiceContext{Config: c,User: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),}
}
4、api服务逻辑层获取rpc服务数据
user/api/internal/logic/userlogic.go
package logicimport ("context""errors""go-zero-user/rpc/user""strconv""go-zero-user/api/internal/svc""go-zero-user/api/internal/types""github.com/zeromicro/go-zero/core/logx"
)type UserLogic struct {logx.Loggerctx context.ContextsvcCtx *svc.ServiceContext
}func NewUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *UserLogic {return &UserLogic{Logger: logx.WithContext(ctx),ctx: ctx,svcCtx: svcCtx,}
}func (l *UserLogic) User(req *types.UserReq) (resp *types.UserResp, err error) {if req.Id == 0 {return nil, errors.New("用户ID不能为空")}// todo: add your logic here and delete this linegetUsers, err := l.svcCtx.User.GetUser(l.ctx, &user.UserRequest{Id: strconv.FormatInt(req.Id, 10),})if err != nil {return nil, err}id, err := strconv.Atoi(getUsers.Id)resp = &types.UserResp{Id: int64(id),Name: getUsers.Name,Phone: getUsers.Phone,}return resp, nil
}