一、go-zero微服务环境安装
-
1、
go-zero脚手架的安装go install github.com/zeromicro/go-zero/tools/goctl@latest -
2、
etcd的安装下载地址根据自己电脑操作系统下载对应的版本,具体的使用自己查阅文章
二、创建一个user-rpc服务
-
1、定义
user.proto文件syntax = "proto3"; package user; option go_package="./user"; service User { rpc FindById(FindByIdReq) returns (FindByIdResp); } message FindByIdReq{ int64 id = 1; } message FindByIdResp { int64 id = 1; string username = 2; } -
2、使用命令生成对应的项目文件
goctl rpc protoc ./user.proto --go_out=. --go-grpc_out=. --zrpc_out=./ -
3、安装对应的依赖包
go mod tidy -
4、运行
user服务go run user.go -
5、在
etcd中查看服务是否已经注册成功etcdctl get --prefix user.rpc -
6、模拟业务代码返回数据
func (l *FindByIdLogic) FindById(in *user.FindByIdReq) (*user.FindByIdResp, error) { return &user.FindByIdResp{ Id: in.Id, Username: "哈哈哈", }, nil } -
7、使用
apifox可以直接调用rpc的服务,引入文件
三、在提供restful api接口端调用rpc服务返回数据给前端
-
1、创建一个
user-api的项目 -
2、创建描述文件
syntax = "v1" type GetUserReq { Id int64 `path:"id"` // 主键id } type GetUserResp { Id int64 `json:"id"` // 用户id Username string `json:"username"` // 用户名 } @server( prefix: api/v1/user group: user ) service user-api { @doc "根据用户id获取用户新" @handler GetUserByIdApi get /:id (GetUserReq) returns (GetUserResp) } -
3、使用脚本生成对应的项目文件
goctl api go -api *.api -dir . --style=gozero -
4、在
user-api的配置文件中引入rpc服务的配置Name: user-api Host: 0.0.0.0 Port: 8888 UserRpc: Etcd: Hosts: - 127.0.0.1:2379 Key: user.rpc -
5、在
apps/user-api/internal/config/config.go创建服务的配置type Config struct { rest.RestConf UserRpc zrpc.RpcClientConf } -
6、在
apps/user-api/internal/svc/servicecontext.go依赖注入rpc服务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)), } } -
7、模拟实现业务代码
func (l *GetUserByIdApiLogic) GetUserByIdApi(req *types.GetUserReq) (resp *types.GetUserResp, err error) { // 模拟业务开发 findByIdResp, err := l.svcCtx.UserRpc.FindById(l.ctx, &user.FindByIdReq{ Id: req.Id, }) if err != nil { return &types.GetUserResp{}, errors.New("查询失败") } return &types.GetUserResp{ Id: findByIdResp.Id, Username: findByIdResp.Username, }, nil } -
8、直接浏览模拟请求
http://localhost:8888/api/v1/user/1



















