文章目錄
- 1.goctl 概述
- 2.go-zero 需要安裝的組件
- 3.生成 api
- 4.生成 rpc
1.goctl 概述
goctl支持多種rpc,較為流行的是google開源的grpc,這里主要介紹goctl rpc protoc的代碼生成與使用。protoc是grpc的命令,作用是將proto buffer文件轉化為相應語言的代碼。
goctl 是 go-zero 的內置腳手架,是提升開發效率的一大利器,可以一鍵生成代碼、文檔、部署 k8s yaml、dockerfile 等。
goctl安裝:
go install github.com/zeromicro/go-zero/tools/goctl@latest
go-zero框架設計:
客戶端 -> Api -> Service -> 緩存 -> Db
- 客戶端: IOS, Android, web, PC
- Api: Http, 鑒權, 加密, 日志, 異常捕獲, 監控, 數據統計, 并發, 鏈路跟蹤, 超時, 熔斷, 降級
- Service: gRPC, 緩存, 日志, 異常捕獲, 監控, 數據統計, 并發, 鏈路跟蹤, 超時, 熔斷, 降級
2.go-zero 需要安裝的組件
- protoc
- protoc-gen-go
- protoc-gen-go-grpc
- goctl
Protobuf下載安裝:
https://github.com/protocolbuffers/protobuf/releases
將下載的文件解壓,將解壓后的bin目錄加入到環境變量的path下。
下載 goctl, proto-gen-go, proto-gen-go-grpc:
go install github.com/zeromicro/go-zero/tools/goctl@latestgoctl env check -i -f --verbosego install google.golang.org/protobuf/cmd/protoc-gen-go@v1.26go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@v1.1
3.生成 api
goctl api new api
logic/apilogic.go
package logicimport ("context""go-zero-demo01/user/api/internal/svc""go-zero-demo01/user/api/internal/types""github.com/zeromicro/go-zero/core/logx"
)type ApiLogic struct {logx.Loggerctx context.ContextsvcCtx *svc.ServiceContext
}func NewApiLogic(ctx context.Context, svcCtx *svc.ServiceContext) *ApiLogic {return &ApiLogic{Logger: logx.WithContext(ctx),ctx: ctx,svcCtx: svcCtx,}
}func (l *ApiLogic) Api(req *types.Request) (resp *types.Response, err error) {// todo: add your logic here and delete this linereturn &types.Response{Message: "api success",}, nil
}
cd api
go mod tidy
go run api.go
4.生成 rpc
goctl rpc new user
或者直接提供goland中的goctl的插件生成rpc的結構。
user.proto
syntax = "proto3";package user;option go_package = './user';message UserReq {string id = 1;
}message UserResp {string id = 1;string name = 2;
}service User {rpc getUser(UserReq) returns (UserResp);
}
etcd:
go run user.go
利用apifox打開grpc的接口: