目录
一、Go framework
1、Kratos 介绍
1.1、Kratos 框架开发依赖安装
2、初始化 Kratos 项目
3、使用 Protobuf 、生成 Go 代码
3.1、增加proto文件模板
3.2、修改proto文件模板
3.3、根据修改完的模板文件生成客户端代码
3.4、根据修改完的模板文件生成服务端代码
4、将生成的服务代码注册到 gRPC 服务中
4.3、生成依赖注入代码
4.4、运行项目
4.5、使用 Apipost 测试接口
一、Go framework
框架 | Github | 开源时间 | 开源方 |
Kratos | https://github.com/go-kratos/kratos | 2019 | Bilibili |
go-kit | https://github.com/go-kit/kit/ | 2015 | 团队开源 |
go-zero | https://github.com/tal-tech/go-zero | 2020 | 团队开源 |
TarsGo | https://github.com/TarsCloud/TarsGo | 2018 | 腾讯 |
Jupiter | https://github.com/douyu/jupiter | 2020 | 斗鱼开源 |
Istio | https://github.com/istio/istio | 2017 | Google、IBM、Lyft开源 |
Kitex | https://github.com/cloudwego/kitex | 2020 | 字节跳动 |
Go-micro(m3o) | https://github.com/asim/go-micro | 2015 | Micro Sercives,Inc |
Dubbo-go | https://github.com/apache/dubbo-go | 2019 | 阿里 |
1、Kratos 介绍
Kratos 是一套由 Bilibili 开源的轻量级 Go 微服务框架,包含大量微服务相关框架及工具。Kratos(奎托斯)是希腊神话中的战神,其主要经历是由凡人成为战神并展开弑神屠杀。
Kratos官网
1.1、Kratos 框架开发依赖安装
1、Go语言环境,All releases - The Go Programming Language
$ go version
go version go1.20.6 windows/amd64$ go env -w GO111MODULE=on$ go env -w GOPROXY=https://goproxy.cn,direct
2、protoc,Protocol Compiler 编辑器 下载Releases · protocolbuffers/protobuf · GitHub
下载完直接解压,配置到path环境变量中
$ protoc --version
libprotoc 3.21.6
3、protoc-gen-go,Protoc 的插件,用于生成 Go 代码
go 语言开发的插件,使用 go install 安装
# 安装最新版本
$ go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
$ go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest# 测试
$ protoc-gen-go --version
protoc-gen-go v1.31.0
$ protoc-gen-go-grpc -version
protoc-gen-go-grpc 1.3.0
4、kratos,kratos 框架配套的脚手架工具
$ go install github.com/go-kratos/kratos/cmd/kratos/v2@latest# 测试
$ kratos -v
kratos version v2.7.0
2、初始化 Kratos 项目
1、使用 Kratos完成第一个验证码校验服务verifyCode。
D:\GIT_workspace\go-valet-driving-system\backend>kratos new verifyCode
🚀 Creating service verifyCode, layout repo is https://github.com/go-kratos/kratos-layout.git, please wait a moment.Cloning into 'C:\Users\Administrator\.kratos\repo\github.com\go-kratos/kratos-layout@main'...[32mCREATED[0m D:\GIT_workspace\go-valet-driving-system\backend\verifyCode\.gitignore (590 bytes)
[32mCREATED[0m D:\GIT_workspace\go-valet-driving-system\backend\verifyCode\Dockerfile (483 bytes)
........
.......
[32mCREATED[0m D:\GIT_workspace\go-valet-driving-system\backend\verifyCode\third_party\validate\validate.proto (32133 bytes)🍺 Project creation succeeded [32mverifyCode[0m
💻 Use the following command to start the project 👇:[37m$ cd verifyCode[0m
[37m$ go generate ./...[0m
[37m$ go build -o ./bin/ ./... [0m
[37m$ ./bin/verifyCode -conf ./configs
[0m🤝 Thanks for using Kratos📚 Tutorial: https://go-kratos.dev/docs/getting-started/start
该布局提供了最基本的目录结构和一个用于测试的 HTTP 和 gRPC 接口。
2、进入项目目录,拉取依赖
$ go mod tidyD:\GIT_workspace\go-valet-driving-system\backend>cd verifyCodeD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>go mod tidy
go: downloading github.com/google/wire v0.5.0
go: downloading github.com/go-kratos/kratos/v2 v2.7.0
....
3、运行项目前,需要先生成相应源码,主要是使用了 wire 的依赖注入相关代码:
$ go get github.com/google/wire/cmd/wire
$ go generate ./...D:\GIT_workspace\go-valet-driving-system\backend\verifyCode>go get github.com/google/wire/cmd/wire
go: downloading github.com/google/subcommands v1.0.1
go: downloading golang.org/x/tools v0.6.0
go: downloading golang.org/x/mod v0.8.0D:\GIT_workspace\go-valet-driving-system\backend\verifyCode>go generate ./...
wire: verifyCode/cmd/verifyCode: wrote D:\GIT_workspace\go-valet-driving-system\backend\verifyCode\cmd\verifyCode\wire_gen.go
4、运行项目,使用 kratos 工具:
$ kratos runD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>kratos run
2023/08/24 23:32:51 maxprocs: Leaving GOMAXPROCS=8: CPU quota undefined
DEBUG msg=config loaded: config.yaml format: yaml
INFO ts=2023-08-24T23:32:52+08:00 caller=http/server.go:317 service.id=MS-TGOOFNKABBOB service.name= service.version= trace.id= span.id= msg=[HTTP] server listening on: [::]:8000
INFO ts=2023-08-24T23:32:52+08:00 caller=grpc/server.go:212 service.id=MS-TGOOFNKABBOB service.name= service.version= trace.id= span.id= msg=[gRPC] server listening on: [::]:9000#以上信息,表示项目运行成功,正在监听 HTTP 8000, gRPC 9000 端口。
测试:http://localhost:8000/helloworld/lwz
helloworld:是kratos生成时默认生成的接口
使用kratos创建项目的步骤
$ kratos new projectName_xxx
$ cd projectName_xxx
$ go mod tidy
$ go get github.com/google/wire/cmd/wire
$ go generate ./...
$ kratos run
3、使用 Protobuf 、生成 Go 代码
可以看到api\helloworld\v1\greeter.proto文件。
使用 .proto 文件定义接口,基于 .proto 文件生成基础代码。
3.1、增加proto文件模板
$ kratos proto add xxx_path/xxx.protoD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>kratos proto add api/verifyCode/verifyCode.protoD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>
3.2、修改proto文件模板
默认生成带增删改查接口,看需求删改。
syntax = "proto3";package api.verifyCode;// 生成的go代码所在的包
option go_package = "verifyCode/api/verifyCode;verifyCode";
option java_multiple_files = true;
option java_package = "api.verifyCode";// 定义 VerifyCode 服务
service VerifyCode {rpc CreateVerifyCode (CreateVerifyCodeRequest) returns (CreateVerifyCodeReply);rpc UpdateVerifyCode (UpdateVerifyCodeRequest) returns (UpdateVerifyCodeReply);rpc DeleteVerifyCode (DeleteVerifyCodeRequest) returns (DeleteVerifyCodeReply);rpc GetVerifyCode (GetVerifyCodeRequest) returns (GetVerifyCodeReply);rpc ListVerifyCode (ListVerifyCodeRequest) returns (ListVerifyCodeReply);
}message CreateVerifyCodeRequest {}
message CreateVerifyCodeReply {}message UpdateVerifyCodeRequest {}
message UpdateVerifyCodeReply {}message DeleteVerifyCodeRequest {}
message DeleteVerifyCodeReply {}message GetVerifyCodeRequest {}
message GetVerifyCodeReply {}message ListVerifyCodeRequest {}
message ListVerifyCodeReply {}
修改,只保留获取验证码
syntax = "proto3";package api.verifyCode;
// 生成的go代码所在的包
option go_package = "verifyCode/api/verifyCode;verifyCode";
// 定义 VerifyCode 服务
service VerifyCode {rpc GetVerifyCode (GetVerifyCodeRequest) returns (GetVerifyCodeReply);
}
// 类型常量
enum TYPE {DEFAULT = 0;DIGIT = 1;LETTER = 2;MIXED = 3;
};
// 定义 GetVerifyCodeRequest 消息
message GetVerifyCodeRequest {// 验证码长度uint32 length = 1;// 验证码类型TYPE type = 2;
}
// 定义 GetVerifyCodeReply 消息
message GetVerifyCodeReply {// 生成的验证码string code = 1;
}
3.3、根据修改完的模板文件生成客户端代码
$ kratos proto client xxx_path/xxxx.protoD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>kratos proto client api/verifyCode/verifyCode.proto
go install github.com/go-kratos/kratos/cmd/kratos/v2@latest
go install github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2@latest
go: downloading github.com/go-kratos/kratos/cmd/protoc-gen-go-http/v2 v2.0.0-20230823024326-a09f4d8ebba9
go: downloading github.com/go-kratos/kratos/cmd/protoc-gen-go-http v0.0.0-20210217095515-c4e4aa563867
go: downloading google.golang.org/genproto v0.0.0-20220519153652-3a47de7e79bd
go: downloading google.golang.org/protobuf v1.28.0
go install github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2@latest
go: downloading github.com/go-kratos/kratos/cmd/protoc-gen-go-errors v0.0.0-20210217095515-c4e4aa563867
go: downloading github.com/go-kratos/kratos/cmd/protoc-gen-go-errors/v2 v2.0.0-20230823024326-a09f4d8ebba9
go: downloading golang.org/x/text v0.3.8
go install google.golang.org/protobuf/cmd/protoc-gen-go@latest
go install google.golang.org/grpc/cmd/protoc-gen-go-grpc@latest
go install github.com/google/gnostic/cmd/protoc-gen-openapi@latest
go: downloading github.com/google/gnostic v0.6.9
go: downloading google.golang.org/protobuf v1.27.1
go: downloading google.golang.org/genproto v0.0.0-20220107163113-42d7afdf6368
go: downloading gopkg.in/yaml.v3 v3.0.0-20200615113413-eeeca48fe776
go: downloading github.com/golang/protobuf v1.5.2
proto: api/verifyCode/verifyCode.proto
代码会生成在 api/verifyCode/ 目录中:
# 类型定义代码
api/verifyCode/verifyCode.pb.go
# gRPC服务定义代码
api/verifyCode/verifyCode_grpc.pb.go
# 注意 http 代码只会在 proto 文件中声明了 http 时才会生成。
api/verifyCode/verifyCode_http.pb.go
注意:生成的以上代码不需要手动编辑。
3.4、根据修改完的模板文件生成服务端代码
$ kratos proto server api/verifyCode/verifyCode.proto -t internal/service# -t 选项指定生成文件所在位置,代码会生成在 internal/service 目录中verifycode.goD:\GIT_workspace\go-valet-driving-system\backend\verifyCode> kratos proto server api/verifyCode/verifyCode.proto -t internal/service
internal\service\verifycode.go
internal/service/verifycode.go
package serviceimport ("context"pb "verifyCode/api/verifyCode"
)type VerifyCodeService struct {pb.UnimplementedVerifyCodeServer
}func NewVerifyCodeService() *VerifyCodeService {return &VerifyCodeService{}
}func (s *VerifyCodeService) GetVerifyCode(ctx context.Context, req *pb.GetVerifyCodeRequest) (*pb.GetVerifyCodeReply, error) {return &pb.GetVerifyCodeReply{}, nil
}
至此,通过编写 .proto 文件来生成接口基础代码的工作就完成了。
接下来还需要将生成的服务代码注册到 gRPC 服务中。
4、将生成的服务代码注册到 gRPC 服务中
使用Golang软件打开代码编辑,方便导入包信息。
4.1、更新 internal/service/service.go 文件:
// ProviderSet is service providers.
var ProviderSet = wire.NewSet(NewGreeterService, NewVerifyCodeService)
在以上的 `wire.NewSet()` 调用中,添加第二个参数 NewVerifyCodeService。这个函数是用来生成 VerifyCodeService 服务的,定义在internal/service/verifycode.go 中。以上代码的意思就是告知 wire 依赖注入系统,如果需要 VerifyCodeService 的话,使用 NewVerifyCodeService 函数来构建。
4.2、更新 internal/server/grpc.go 文件:
在 NewGRPCServer 函数中:
1.增加一个参数
2.在函数体中,增加一行代码
用于将 VerifyCodeService 注册到 gRPC 服务中:
internal/server/grpc.go
package serverimport (v1 "verifyCode/api/helloworld/v1""verifyCode/api/verifyCode""verifyCode/internal/conf""verifyCode/internal/service""github.com/go-kratos/kratos/v2/log""github.com/go-kratos/kratos/v2/middleware/recovery""github.com/go-kratos/kratos/v2/transport/grpc"
)// NewGRPCServer new a gRPC server.
func NewGRPCServer(c *conf.Server, greeter *service.GreeterService,// 增加下行,传递一个参数verifyCodeService *service.VerifyCodeService,logger log.Logger) *grpc.Server {var opts = []grpc.ServerOption{grpc.Middleware(recovery.Recovery(),),}if c.Grpc.Network != "" {opts = append(opts, grpc.Network(c.Grpc.Network))}if c.Grpc.Addr != "" {opts = append(opts, grpc.Address(c.Grpc.Addr))}if c.Grpc.Timeout != nil {opts = append(opts, grpc.Timeout(c.Grpc.Timeout.AsDuration()))}srv := grpc.NewServer(opts...)v1.RegisterGreeterServer(srv, greeter)// 增加下行,将 VerifyCodeService 注册到 srv 中verifyCode.RegisterVerifyCodeServer(srv, verifyCodeService)return srv
}
4.3、生成依赖注入代码
$ go generate ./...D:\GIT_workspace\go-valet-driving-system\backend\verifyCode>go generate ./...
wire: verifyCode/cmd/verifyCode: wrote D:\GIT_workspace\go-valet-driving-system\backend\verifyCode\cmd\verifyCode\wire_gen.go
4.4、运行项目
$ kratos runD:\GIT_workspace\go-valet-driving-system\backend\verifyCode>kratos run
2023/08/26 00:38:34 maxprocs: Leaving GOMAXPROCS=8: CPU quota undefined
DEBUG msg=config loaded: config.yaml format: yaml
INFO ts=2023-08-26T00:38:35+08:00 caller=grpc/server.go:212 service.id=MS-TGOOFNKABBOB service.name= service.version= trace.id= span.id= msg=[gRPC] server listening on: [::]:9000
INFO ts=2023-08-26T00:38:35+08:00 caller=http/server.go:317 service.id=MS-TGOOFNKABBOB service.name= service.version= trace.id= span.id= msg=[HTTP] server listening on: [::]:8000
4.5、使用 Apipost 测试接口
Apipost官网
Apipost可以测试grpc协议接口
新建grpc接口测试,导入proto文件, 测试地址,调用。返回值信息。
上面有返回信息代表正常调用
{"code": ""
}
Apipost也可以测试http协议接口
Web framework-Gin
Go framework-Beego
Golang学习+深入(一)
年轻不怕输!
谁能比别人领先一步掌握新技术,谁就在竞争中赢得了先机。