该文章为学习开源微服务框架kratos的学习笔记!官方文档见:简介 | Kratos
Kratos 一套轻量级 Go 微服务框架,包含大量微服务相关框架及工具。
通过 Kratos 工具生成的 Go工程化项目模板如下:
application
|____api
| |____helloworld
| | |____v1
| | |____errors
|____cmd
| |____helloworld
|____configs
|____internal
| |____conf
| |____data
| |____biz
| |____service
| |____server
|____test
|____pkg
|____go.mod
|____go.sum
|____LICENSE
|____README.md
其中有关依赖注入的详细文档见:Go工程化 - 依赖注入 | Kratos
以下是我自己总结的kratos依赖注入关系图:
运用 google/wire 工具将上述依赖注入生成具体的kratos项目代码示例:
原始 wire.go 代码:
// initApp init kratos application.
func initApp(*conf.Server, *conf.Data, *conf.Auth, log.Logger) (*kratos.App, func(), error) {panic(wire.Build(server.ProviderSet, data.ProviderSet, biz.ProviderSet, service.ProviderSet, newApp))
}
工具生成的代码wire_gen.go:
// initApp init kratos application.
func initApp(confServer *conf.Server, confData *conf.Data, auth *conf.Auth, logger log.Logger) (*kratos.App, func(), error) {dataData, cleanup, err := data.NewData(confData, logger)if err != nil {return nil, nil, err}articleRepo := data.NewArticleRepo(dataData, logger)articleUsecase := biz.NewArticleUsecase(articleRepo, logger)blogService := service.NewBlogService(articleUsecase, logger)userRepo := data.NewUserRepo(dataData, logger)encryptService := biz.NewEncryptService(auth)accountUseCase := biz.NewAccountUseCase(logger, auth, userRepo, encryptService)accountService := service.NewAccountService(logger, accountUseCase)httpServer := server.NewHTTPServer(confServer, logger, blogService, accountService)grpcServer := server.NewGRPCServer(confServer, logger, blogService, accountService)app := newApp(logger, httpServer, grpcServer)return app, func() {cleanup()}, nil
}