文章目录
- 1.注意事项
- 2.服务划分及创建
- 2.1 用户微服务
- 2.2 订单微服务
- 3.启动服务
- 3.1 etcd 服务启动
- 3.2 微服务启动
- 3.3 测试访问
1.注意事项
go-zero微服务的注册中心默认使用的是Etcd。
本小节将以一个订单服务调用用户服务来简单演示一下,其实订单服务是api服务,用户服务是rpc服务。
这里的创建步骤和官方文档的不一致,做了部分优化,前提是已经了解了go-zero微服务调用及配置流程。初学者还是推荐按照官方文档操作。
2.服务划分及创建
2.1 用户微服务
syntax = "proto3";package user;// protoc-gen-go 版本大于1.4.0, proto文件需要加上go_package,否则无法生成
option go_package = "./user";message IdRequest {string id = 1;
}message UserResponse {// 用户idstring id = 1;// 用户名称string name = 2;// 用户性别string gender = 3;
}service User {rpc getUser(IdRequest) returns(UserResponse);
}
user服务的代码逻辑主要是在 internal/logic/xxxlogic.go里填写,xxxlogic.go的xxx指的是在.proto中定义的方法名的小写。
rpc getUser(IdRequest) returns(UserResponse);
对应 internal/logic/getuserlogic.go,一个rpc方法对应一个logic.go。在logic.go中可以进一步处理请求,比如操作数据库,Redis等。
package logicimport ("context""go-zero-micro/rpc/user/internal/svc""go-zero-micro/rpc/user/user""github.com/zeromicro/go-zero/core/logx"
)type GetUserLogic struct {ctx context.ContextsvcCtx *svc.ServiceContextlogx.Logger
}func NewGetUserLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetUserLogic {return &GetUserLogic{ctx: ctx,svcCtx: svcCtx,Logger: logx.WithContext(ctx),}
}func (l *GetUserLogic) GetUser(in *user.IdRequest) (*user.UserResponse, error) {// todo: add your logic here and delete this lineuserRes :=&user.UserResponse{Id: in.Id,Gender: "男",}if in.Id == "1" {userRes.Name = "admin"}else {userRes.Name = "test"}return userRes, nil
}
2.2 订单微服务
在order服务下添加order.api文件,增加getUser方法:
syntax = "v1"type Request {Name string `path:"name,options=you|me"`
}type Response {Message string `json:"message"`
}type (OrderReq {Id string `path:"id"`}OrderResp {Id string `json:"id"`Name string `json:"name"`UserName string `json:"userName"`}
)service order-api {@handler OrderHandlerget /from/:name (Request) returns (Response)@handler GetOrderHandlerget /api/order/get/:id (OrderReq) returns (OrderResp)
}
执行生成order服务的命令
order服务调用user服务需要改动3个地方。
- etc/order.yaml
- internal/config/config.go
- internal/svc/servicecontext.go
order.yaml
Name: order-api
Host: 0.0.0.0
Port: 8888
UserRpc:Etcd:Hosts:- localhost:2379Key: user.rpc
user.yaml
Name: user.rpc
ListenOn: 0.0.0.0:8080
Etcd:Hosts:- 127.0.0.1:2379Key: user.rpc
加入user服务的RPC。
config.go
package configimport ("github.com/zeromicro/go-zero/rest""github.com/zeromicro/go-zero/zrpc"
)type Config struct {rest.RestConfUserRpc zrpc.RpcClientConf
}
user服务接口加入到 order服务的ServiceContext中。
servicecontext.go
package svcimport ("github.com/zeromicro/go-zero/zrpc""mall/order/internal/config""mall/user/userclient"
)type ServiceContext struct {Config config.ConfigUserRpc userclient.User
}func NewServiceContext(c config.Config) *ServiceContext {return &ServiceContext{Config: c,UserRpc: userclient.NewUser(zrpc.MustNewClient(c.UserRpc)),}
}
order服务修改 getorderlogic.go。
getorderlogic.go
package logicimport ("context""github.com/pkg/errors""mall/user/user""strconv""mall/order/internal/svc""mall/order/internal/types""github.com/zeromicro/go-zero/core/logx"
)type GetOrderLogic struct {logx.Loggerctx context.ContextsvcCtx *svc.ServiceContext
}func NewGetOrderLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetOrderLogic {return &GetOrderLogic{Logger: logx.WithContext(ctx),ctx: ctx,svcCtx: svcCtx,}
}func (l *GetOrderLogic) GetOrder(req *types.OrderReq) (resp *types.OrderResp, err error) {// todo: add your logic here and delete this lineId, err := strconv.Atoi(req.Id)if err != nil {return nil, err}if Id < 1 {return nil, errors.New("用户不存在")}userRes, err := l.svcCtx.UserRpc.GetUser(l.ctx, &user.IdRequest{Id: req.Id,})if err != nil {return nil, err}return &types.OrderResp{Id: req.Id,Name: userRes.Name,UserName: "userName",}, nil
}
3.启动服务
3.1 etcd 服务启动
3.2 微服务启动
user.go
package mainimport ("flag""fmt""mall/user/internal/config""mall/user/internal/server""mall/user/internal/svc""mall/user/user""github.com/zeromicro/go-zero/core/conf""github.com/zeromicro/go-zero/core/service""github.com/zeromicro/go-zero/zrpc""google.golang.org/grpc""google.golang.org/grpc/reflection"
)var configFile = flag.String("f", "etc/user.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c)ctx := svc.NewServiceContext(c)s := zrpc.MustNewServer(c.RpcServerConf, func(grpcServer *grpc.Server) {user.RegisterUserServer(grpcServer, server.NewUserServer(ctx))if c.Mode == service.DevMode || c.Mode == service.TestMode {reflection.Register(grpcServer)}})defer s.Stop()fmt.Printf("Starting rpc server at %s...\n", c.ListenOn)s.Start()
}
order.go
package mainimport ("flag""fmt""mall/order/internal/config""mall/order/internal/handler""mall/order/internal/svc""github.com/zeromicro/go-zero/core/conf""github.com/zeromicro/go-zero/rest"
)var configFile = flag.String("f", "etc/order.yaml", "the config file")func main() {flag.Parse()var c config.Configconf.MustLoad(*configFile, &c)server := rest.MustNewServer(c.RestConf)defer server.Stop()ctx := svc.NewServiceContext(c)handler.RegisterHandlers(server, ctx)fmt.Printf("Starting server at %s:%d...\n", c.Host, c.Port)server.Start()
}
3.3 测试访问
http://localhost:8888/api/order/get/1
http://localhost:8888/api/order/get/2
http://localhost:8888/api/order/get/-1