文章目錄
- 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