kratos源码分析系列(1)(kvm源码解析与应用 pdf)
liuian 2025-05-09 20:03 28 浏览
https://github.com/go-kratos/kratos是b站开源的一个微服务框架,整体来看它结合grpc生态中的grpc-gateway,以及wire依赖注入和众多常用的trace,matrix,log等中间件提供了一套微服务框架。我先尝试一下使用。
安装
% go install github.com/go-kratos/kratos/cmd/kratos/v2@latest
创建demo
% kratos new helloworld
Creating service helloworld, layout repo is https://github.com/go-kratos/kratos-layout.git, please wait a moment.
当前分支没有跟踪信息。
请指定您要合并哪一个分支。
详见 git-pull(1)。
git pull <远程> <分支>
如果您想要为此分支创建跟踪信息,您可以执行:
git branch --set-upstream-to=origin/<分支> master
ERROR: Failed to create project(exit status 1)
这是由于国内环境拉项目模板会失败。可以换个源。
% kratos new helloworld -r https://gitee.com/go-kratos/kratos-layout.git
Creating service helloworld, layout repo is https://gitee.com/go-kratos/kratos-layout.git, please wait a moment.
正克隆到 '/Users/xiazemin/.kratos/repo/gitee.com/go-kratos/kratos-layout@main'...
CREATED helloworld/.gitignore (528 bytes)
CREATED helloworld/Dockerfile (459 bytes)
CREATED helloworld/LICENSE (1066 bytes)
CREATED helloworld/Makefile (2399 bytes)
CREATED helloworld/README.md (1062 bytes)
CREATED helloworld/api/helloworld/v1/error_reason.pb.go (4991 bytes)
CREATED helloworld/api/helloworld/v1/error_reason.proto (289 bytes)
CREATED helloworld/api/helloworld/v1/greeter.pb.go (8074 bytes)
CREATED helloworld/api/helloworld/v1/greeter.proto (678 bytes)
CREATED helloworld/api/helloworld/v1/greeter_grpc.pb.go (3560 bytes)
CREATED helloworld/api/helloworld/v1/greeter_http.pb.go (2139 bytes)
CREATED helloworld/cmd/helloworld/main.go (1712 bytes)
CREATED helloworld/cmd/helloworld/wire.go (584 bytes)
CREATED helloworld/cmd/helloworld/wire_gen.go (1068 bytes)
CREATED helloworld/configs/config.yaml (266 bytes)
CREATED helloworld/go.mod (990 bytes)
CREATED helloworld/go.sum (18962 bytes)
CREATED helloworld/internal/biz/README.md (6 bytes)
CREATED helloworld/internal/biz/biz.go (128 bytes)
CREATED helloworld/internal/biz/greeter.go (1235 bytes)
CREATED helloworld/internal/conf/conf.pb.go (20782 bytes)
CREATED helloworld/internal/conf/conf.proto (761 bytes)
CREATED helloworld/internal/data/README.md (7 bytes)
CREATED helloworld/internal/data/data.go (472 bytes)
CREATED helloworld/internal/data/greeter.go (834 bytes)
CREATED helloworld/internal/server/grpc.go (825 bytes)
CREATED helloworld/internal/server/http.go (829 bytes)
CREATED helloworld/internal/server/server.go (150 bytes)
CREATED helloworld/internal/service/README.md (10 bytes)
CREATED helloworld/internal/service/greeter.go (688 bytes)
CREATED helloworld/internal/service/service.go (136 bytes)
CREATED helloworld/openapi.yaml (1130 bytes)
CREATED helloworld/third_party/README.md (14 bytes)
CREATED helloworld/third_party/errors/errors.proto (411 bytes)
CREATED helloworld/third_party/google/api/annotations.proto (1051 bytes)
CREATED helloworld/third_party/google/api/client.proto (3395 bytes)
CREATED helloworld/third_party/google/api/field_behavior.proto (3011 bytes)
CREATED helloworld/third_party/google/api/http.proto (15140 bytes)
CREATED helloworld/third_party/google/api/httpbody.proto (2671 bytes)
CREATED helloworld/third_party/google/protobuf/any.proto (5909 bytes)
CREATED helloworld/third_party/google/protobuf/api.proto (7734 bytes)
CREATED helloworld/third_party/google/protobuf/compiler/plugin.proto (8754 bytes)
CREATED helloworld/third_party/google/protobuf/descriptor.proto (38497 bytes)
CREATED helloworld/third_party/google/protobuf/duration.proto (4895 bytes)
CREATED helloworld/third_party/google/protobuf/empty.proto (2429 bytes)
CREATED helloworld/third_party/google/protobuf/field_mask.proto (8185 bytes)
CREATED helloworld/third_party/google/protobuf/source_context.proto (2341 bytes)
CREATED helloworld/third_party/google/protobuf/struct.proto (3779 bytes)
CREATED helloworld/third_party/google/protobuf/timestamp.proto (6459 bytes)
CREATED helloworld/third_party/google/protobuf/type.proto (6126 bytes)
CREATED helloworld/third_party/google/protobuf/wrappers.proto (4042 bytes)
CREATED helloworld/third_party/openapi/v3/annotations.proto (2196 bytes)
CREATED helloworld/third_party/openapi/v3/openapi.proto (22082 bytes)
CREATED helloworld/third_party/validate/README.md (81 bytes)
CREATED helloworld/third_party/validate/validate.proto (31270 bytes)
Project creation succeeded helloworld
Use the following command to start the project :
$ cd helloworld
$ go generate ./...
$ go build -o ./bin/ ./...
$ ./bin/helloworld -conf ./configs
Thanks for using Kratos
Tutorial: https://go-kratos.dev/docs/getting-started/start
可以发现模板生成成功了
% cd helloworld
% go mod download
安装wire
% go get github.com/google/wire/cmd/wire@v0.5.0
go get: installing executables with 'go get' in module mode is deprecated.
To adjust and download dependencies of the current module, use 'go get -d'.
To install using requirements of the current module, use 'go install'.
To install ignoring the current module, use 'go install' with a version,
like 'go install example.com/cmd@latest'.
For more information, see https://golang.org/doc/go-get-install-deprecation
or run 'go help get' or 'go help install'.
生成依赖
% go generate ./...
wire: helloworld/cmd/helloworld: wrote /Users/xiazemin/bilibili/kratos/helloworld/cmd/helloworld/wire_gen.go
启动服务
% kratos run
DEBUG msg=config loaded: config.yaml format: yaml
INFO ts=2022-09-04T21:36:08+08:00 caller=server.go:276 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=[HTTP] server listening on: [::]:8000
INFO ts=2022-09-04T21:36:08+08:00 caller=server.go:193 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=[gRPC] server listening on: [::]:9000
INFO ts=2022-09-04T21:36:25+08:00 caller=greeter.go:43 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=CreateGreeter: kratos
^@^@^@^@^CINFO ts=2022-09-04T21:42:10+08:00 caller=server.go:291 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=[HTTP] server stopping
INFO ts=2022-09-04T21:42:10+08:00 caller=server.go:202 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=[gRPC] server stopping
INFO ts=2022-09-04T21:42:10+08:00 caller=data.go:20 service.id=xiazemindeMacBook-Pro.local service.name= service.version= trace.id= span.id= msg=closing the data resources
测试
% curl 'http://127.0.0.1:8000/helloworld/kratos'
{"message":"Hello kratos"}
接着我们看下目录结构
% tree
.
|____cmd
| |____helloworld
| | |____wire_gen.go
| | |____wire.go
| | |____main.go
|____go.mod
|____LICENSE
|____Dockerfile
|____Makefile
|____internal
| |____biz
| | |____README.md
| | |____greeter.go
| | |____biz.go
| |____server
| | |____server.go
| | |____grpc.go
| | |____http.go
| |____service
| | |____service.go
| | |____README.md
| | |____greeter.go
| |____data
| | |____README.md
| | |____data.go
| | |____greeter.go
| |____conf
| | |____conf.proto
| | |____conf.pb.go
|____go.sum
|____README.md
|____third_party
| |____validate
| | |____README.md
| | |____validate.proto
| |____google
| | |____api
| | | |____client.proto
| | | |____http.proto
| | | |____annotations.proto
| | | |____field_behavior.proto
| | | |____httpbody.proto
| | |____protobuf
| | | |____timestamp.proto
| | | |____field_mask.proto
| | | |____api.proto
| | | |____duration.proto
| | | |____struct.proto
| | | |____wrappers.proto
| | | |____source_context.proto
| | | |____any.proto
| | | |____type.proto
| | | |____empty.proto
| | | |____compiler
| | | | |____plugin.proto
| | | |____descriptor.proto
| |____openapi
| | |____v3
| | | |____annotations.proto
| | | |____openapi.proto
| |____README.md
| |____errors
| | |____errors.proto
|____.gitignore
|____configs
| |____config.yaml
|____api
| |____helloworld
| | |____v1
| | | |____greeter_http.pb.go
| | | |____error_reason.proto
| | | |____error_reason.pb.go
| | | |____greeter.pb.go
| | | |____greeter.proto
| | | |____greeter_grpc.pb.go
|____openapi.yaml
具体分层含义可以参考官方文档:
https://go-kratos.dev/docs/intro/layout
.
├── Dockerfile
├── LICENSE
├── Makefile
├── README.md
├── api // 下面维护了微服务使用的proto文件以及根据它们所生成的go文件
│ └── helloworld
│ └── v1
│ ├── error_reason.pb.go
│ ├── error_reason.proto
│ ├── error_reason.swagger.json
│ ├── greeter.pb.go
│ ├── greeter.proto
│ ├── greeter.swagger.json
│ ├── greeter_grpc.pb.go
│ └── greeter_http.pb.go
├── cmd // 整个项目启动的入口文件
│ └── server
│ ├── main.go
│ ├── wire.go // 我们使用wire来维护依赖注入
│ └── wire_gen.go
├── configs // 这里通常维护一些本地调试用的样例配置文件
│ └── config.yaml
├── generate.go
├── go.mod
├── go.sum
├── internal // 该服务所有不对外暴露的代码,通常的业务逻辑都在这下面,使用internal避免错误引用
│ ├── biz // 业务逻辑的组装层,类似 DDD 的 domain 层,data 类似 DDD 的 repo,而 repo 接口在这里定义,使用依赖倒置的原则。
│ │ ├── README.md
│ │ ├── biz.go
│ │ └── greeter.go
│ ├── conf // 内部使用的config的结构定义,使用proto格式生成
│ │ ├── conf.pb.go
│ │ └── conf.proto
│ ├── data // 业务数据访问,包含 cache、db 等封装,实现了 biz 的 repo 接口。我们可能会把 data 与 dao 混淆在一起,data 偏重业务的含义,它所要做的是将领域对象重新拿出来,我们去掉了 DDD 的 infra层。
│ │ ├── README.md
│ │ ├── data.go
│ │ └── greeter.go
│ ├── server // http和grpc实例的创建和配置
│ │ ├── grpc.go
│ │ ├── http.go
│ │ └── server.go
│ └── service // 实现了 api 定义的服务层,类似 DDD 的 application 层,处理 DTO 到 biz 领域实体的转换(DTO -> DO),同时协同各类 biz 交互,但是不应处理复杂逻辑
│ ├── README.md
│ ├── greeter.go
│ └── service.go
└── third_party // api 依赖的第三方proto
├── README.md
├── google
│ └── api
│ ├── annotations.proto
│ ├── http.proto
│ └── httpbody.proto
└── validate
├── README.md
└── validate.proto
首先看下api目录它以
api/helloworld/v1/greeter.proto为模板生成了对应的grpc pb文件和http pb文件,前者是通过proto-gen-go生成的,后者是通过grpc gateway生成的。
我们从main函数开始读下这个模板 cmd/helloworld/main.go核心代码下面两行
app, cleanup, err := wireApp(bc.Server, bc.Data, logger)
if err := app.Run(); err != nil {
wireApp进行了依赖注入,看下wire.go里面声明的依赖
func wireApp(*conf.Server, *conf.Data, log.Logger) (*kratos.App, func(), error) {
panic(wire.Build(server.ProviderSet, data.ProviderSet, biz.ProviderSet, service.ProviderSet, newApp))
}
最后一个参数newApp函数是在main.go里声明的。它new里一个kratos.App对象
func newApp(logger log.Logger, gs *grpc.Server, hs *http.Server) *kratos.App {
return kratos.New(
kratos.ID(id),
kratos.Name(Name),
kratos.Version(Version),
kratos.Metadata(map[string]string{}),
kratos.Logger(logger),
kratos.Server(
gs,
hs,
),
)
}
最后就是通过app.Run启动server进行端口监听的。具体代码实现在
github.com/go-kratos/kratos/v2@v2.4.1/app.go中,可以看到它时结合waitGroup和errorGroup来控制多个server的起动和停止的。
func (a *App) Run() error {
wg := sync.WaitGroup{}
for _, srv := range a.opts.servers {
srv := srv
eg.Go(func() error {
<-ctx.Done() // wait for stop signal
stopCtx, cancel := context.WithTimeout(NewContext(a.opts.ctx, a), a.opts.stopTimeout)
defer cancel()
return srv.Stop(stopCtx)
})
wg.Add(1)
eg.Go(func() error {
wg.Done()
return srv.Start(NewContext(a.opts.ctx, a))
})
}
wg.Wait()
可以看到核心代码是通过waitGroup等待所有的的server停止服务。但是对于每一个服务通过errorGroup来等待当前服务的超时或者完成服务正常结束的。
以上就是main服务的整体流程。下一讲我们分析依赖注入的server,biz,data和serverice。
相关推荐
- MySQL慢查询优化:从explain到索引,DBA手把手教你提升10倍性能
-
数据库性能是应用系统的生命线,而慢查询就像隐藏在系统中的定时炸弹。某电商平台曾因一条未优化的SQL导致订单系统响应时间从200ms飙升至8秒,最终引发用户投诉和订单流失。今天我们就来系统学习MySQL...
- 一文读懂SQL五大操作类别(DDL/DML/DQL/DCL/TCL)的基础语法
-
在SQL中,DDL、DML、DQL、DCL、TCL是按操作类型划分的五大核心语言类别,缩写及简介如下:DDL(DataDefinitionLanguage,数据定义语言):用于定义和管理数据库结构...
- 闲来无事,学学Mysql增、删,改,查
-
Mysql增、删,改,查1“增”——添加数据1.1为表中所有字段添加数据1.1.1INSERT语句中指定所有字段名语法:INSERTINTO表名(字段名1,字段名2,…)VALUES(值1...
- 数据库:MySQL 高性能优化规范建议
-
数据库命令规范所有数据库对象名称必须使用小写字母并用下划线分割所有数据库对象名称禁止使用MySQL保留关键字(如果表名中包含关键字查询时,需要将其用单引号括起来)数据库对象的命名要能做到见名识意,...
- 下载工具合集_下载工具手机版
-
迅雷,在国内的下载地位还是很难撼动的,所需要用到的地方还挺多。缺点就是不开会员,软件会限速。EagleGet,全能下载管理器,支持HTTP(S)FTPMMSRTSP协议,也可以使用浏览器扩展检测...
- mediamtx v1.15.2 更新详解:功能优化与问题修复
-
mediamtxv1.15.2已于2025年10月14日发布,本次更新在功能、性能优化以及问题修复方面带来了多项改进,同时也更新了部分依赖库并提升了安全性。以下为本次更新的详细内容:...
- 声学成像仪:泄露监测 “雷达” 方案开启精准防控
-
声学成像仪背景将声像图与阵列上配装的摄像实所拍的视频图像以透明的方式叠合在一起,就形成了可直观分析被测物产生状态。这种利用声学、电子学和信息处理等技术,变换成人眼可见的图像的技术可以帮助人们直观地认识...
- 最稳存储方案:两种方法将摄像头接入威联通Qu405,录像不再丢失
-
今年我家至少被4位邻居敲门,就是为了查监控!!!原因是小区内部监控很早就停止维护了,半夜老有小黄毛掰车门偷东西,还有闲的没事划车的,车主损失不小,我家很早就配备监控了,人来亮灯有一定威慑力,不过监控设...
- 离岗检测算法_离岗检查内容
-
一、研发背景如今社会许多岗位是严禁随意脱离岗位的,如塔台、保安室、监狱狱警监控室等等,因为此类行为可能会引起重大事故,而此类岗位监督管理又有一定困难,因此促生了智能视频识别系统的出现。二、产品概述及工...
- 消防安全通道占用检测报警系统_消防安全通道占用检测报警系统的作用
-
一、产品概述科缔欧消防安全通道占用检测报警系统,是创新行业智能监督管理方式、完善监管部门动态监控及预警预报体系的信息化手段,是实现平台远程监控由“人为监控”向“智能监控”转变的必要手段。产品致力于设...
- 外出住酒店、民宿如何使用手机检测隐藏的监控摄像头
-
最近,一个家庭在他们的民宿收到了一个大惊喜:客厅里有一个伪装成烟雾探测器的隐藏摄像头,监视着他们的一举一动。隐藏摄像头的存在如果您住在酒店或民宿,隐藏摄像头不应再是您的担忧。对于民宿,房东应报告所有可...
- 基于Tilera众核平台的流媒体流量发生系统的设计
-
曾帅,高宗彬,赵国锋(重庆邮电大学通信与信息工程学院,重庆400065)摘要:设计了一种基于Tilera众核平台高强度的流媒体流量发生系统架构,其主要包括:系统界面管理模块、服务承载模块和流媒体...
- 使用ffmpeg将rtsp流转流实现h5端播放
-
1.主要实现rtsp转tcp协议视频流播放ffmpeg下载安装(公认业界视频处理大佬)a、官网地址:www.ffmpeg.org/b、gitHub:github.com/FFmpeg/FFmp…c、推...
- 将摄像头视频流从Rtsp协议转为websocket协议
-
写在前面很多通过摄像头拿到的视频流格式都是Rtsp协议的,比如:海康威视摄像头。在现代的浏览器中,已经不支持直接播放Rtsp视频流,而且,海康威视提供的本身的webSdk3.3.0视频插件有很多...
- 华芸科技推出安全监控中心2.1 Beta测试版
-
全球独家支持hdmi在线实时监看摄像机画面,具单一、循环或同时监看四频道视频影像,可透过华芸专用红外线遥控器、airemote或是键盘鼠标进行操作,提供摄像机频道增购服务,满足用户弹性扩增频道需...
- 一周热门
- 最近发表
- 标签列表
-
- python判断字典是否为空 (50)
- crontab每周一执行 (48)
- aes和des区别 (43)
- bash脚本和shell脚本的区别 (35)
- canvas库 (33)
- dataframe筛选满足条件的行 (35)
- gitlab日志 (33)
- lua xpcall (36)
- blob转json (33)
- python判断是否在列表中 (34)
- python html转pdf (36)
- 安装指定版本npm (37)
- idea搜索jar包内容 (33)
- css鼠标悬停出现隐藏的文字 (34)
- linux nacos启动命令 (33)
- gitlab 日志 (36)
- adb pull (37)
- python判断元素在不在列表里 (34)
- python 字典删除元素 (34)
- vscode切换git分支 (35)
- python bytes转16进制 (35)
- grep前后几行 (34)
- hashmap转list (35)
- c++ 字符串查找 (35)
- mysql刷新权限 (34)