浅谈go微服务框架Kratos (奎托斯)
Kratos 是 bilibili 开源的一套 Go 微服务框架,包含大量微服务相关框架及工具。
名字来源于:《战神》游戏以希腊神话为背景,讲述由凡人成为战神的奎托斯(Kratos)成为战神并展开弑神屠杀的冒险历程。
前奏安装
代理设置
GOPROXY=goproxy.io/ 最建议设置这个
安装protoc二进制文件
下载地址:github.com/google/prot… win示例:
把该文件夹放到你想要放的地方,然后在系统(或者用户)中添加bin目录环境变量,例:D:\goproject\protoc-3.11.2-win64\bin
安装protobuf库文件
go get -u github.com/golang/protobuf/proto
安装goprotobuf插件
go get github.com/golang/protobuf/protoc-gen-go
安装gogoprotobuf插件和依赖
go get github.com/gogo/protobuf/protoc-gen-gogo //gofast go get github.com/gogo/protobuf/protoc-gen-gofast //依赖 go get github.com/gogo/protobuf/proto go get github.com/gogo/protobuf/gogoproto
安装框架依赖
go get -u google.golang.org/grpc go get google.golang.org/genproto/...
安装kratos tool
go get -u github.com/go-kratos/kratos/tool/kratos
Features
- APIs:协议通信以 HTTP/gRPC 为基础,通过 Protobuf 进行定义;
- Errors:通过 Protobuf 的 Enum 作为错误码定义,以及工具生成判定接口;
- Metadata:在协议通信 HTTP/gRPC 中,通过 Middleware 规范化服务元信息传递;
- Config:支持多数据源方式,进行配置合并铺平,通过 Atomic 方式支持动态配置;
- Logger:标准日志接口,可方便集成三方 log 库,并可通过 fluentd 收集日志;
- Metrics:统一指标接口,可以实现各种指标系统,默认集成 Prometheus;
- Tracing:遵循 OpenTelemetry 规范定义,以实现微服务链路追踪;
- Encoding:支持 Accept 和 Content-Type 进行自动选择内容编码;
- Transport:通用的 HTTP/gRPC 传输层,实现统一的 Middleware 插件支持;
- Registry:实现统一注册中心接口,可插件化对接各种注册中心;
Architecture
Requirments
Go version>=1.12 and GO111MODULE=on
Installation
go get -u github.com/bilibili/kratos/tool/kratos
cd $GOPATH/src
kratos new kratos-demo
通过 kratos new 会快速生成基于kratos库的脚手架代码,如生成 kratos-demo
如只生成bm请加–http
kratos new kratos-demo -o YourName -d YourPath --http
如只生成grpc请加–grpc
kratos new kratos-demo -o YourName -d YourPath --grpc
Build & Run
cd kratos-demo/cmd
go build
./cmd -conf ../configs
特别注意:如果不是MacOS系统,需要自己进行手动安装protoc,用于生成的示例项目api目录下的proto文件并不会自动生成对应的.pb.go和.bm.go文件。