一、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"` // 用戶idUsername string `json:"username"` // 用戶名 } @server(prefix: api/v1/usergroup: user ) service user-api {@doc "根據用戶id獲取用戶新"@handler GetUserByIdApiget /: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: 8888UserRpc:Etcd:Hosts:- 127.0.0.1:2379Key: user.rpc
-
5、在
apps/user-api/internal/config/config.go
創建服務的配置type Config struct {rest.RestConfUserRpc zrpc.RpcClientConf }
-
6、在
apps/user-api/internal/svc/servicecontext.go
依賴注入rpc
服務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)),} }
-
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