Kratos快速入门 4 months ago
Kratos 是一个轻量级的 Go 微服务框架,适用于构建高性能、可扩展的微服务应用。
以下是使用 Kratos 的基本步骤:
1. 安装 Kratos
确保已安装 Go(1.16 或更高版本),然后使用以下命令安装 Kratos CLI 工具:
go install github.com/go-kratos/kratos/cmd/kratos/v2@latest
安装完成后,检查是否安装成功:
kratos -v
2. 创建新项目
使用 Kratos CLI 快速创建一个新项目:
kratos new helloworld
这将生成一个名为 helloworld
的项目,目录结构如下:
helloworld/
├── api/ # API 定义(Protobuf)
├── cmd/ # 主程序入口
├── configs/ # 配置文件
├── internal/ # 业务逻辑代码
│ ├── conf/ # 配置结构定义
│ ├── data/ # 数据层(数据库操作)
│ ├── server/ # 服务层(HTTP/gRPC 服务)
│ ├── service/ # 业务逻辑实现
│ └── biz/ # 业务逻辑核心
└── Makefile # 构建脚本
3. 编写 API 定义
在 api/helloworld/v1/
目录下,使用 Protobuf 定义服务接口。例如:
syntax = "proto3";
package helloworld.v1;
option go_package = "github.com/yourname/helloworld/api/helloworld/v1;v1";
service Greeter {
rpc SayHello (HelloRequest) returns (HelloReply);
}
message HelloRequest {
string name = 1;
}
message HelloReply {
string message = 1;
}
4. 生成代码
使用 kratos proto
命令生成代码:
kratos proto client api/helloworld/v1/helloworld.proto
kratos proto server api/helloworld/v1/helloworld.proto -t internal/service
这将生成 gRPC 和 HTTP 的服务端和客户端代码。
5. 实现业务逻辑
在 internal/service/
目录下实现业务逻辑。例如:
package service
import (
"context"
"helloworld/internal/biz"
v1 "helloworld/api/helloworld/v1"
)
type GreeterService struct {
v1.UnimplementedGreeterServer
uc *biz.GreeterUsecase
}
func NewGreeterService(uc *biz.GreeterUsecase) *GreeterService {
return &GreeterService{uc: uc}
}
func (s *GreeterService) SayHello(ctx context.Context, req *v1.HelloRequest) (*v1.HelloReply, error) {
return &v1.HelloReply{Message: "Hello " + req.Name}, nil
}
6. 配置服务
在 configs/
目录下编辑配置文件(如 config.yaml
),定义服务端口、数据库连接等信息。
7. 运行服务
使用以下命令启动服务:
kratos run
服务默认会启动 HTTP 和 gRPC 服务。
8. 测试服务
使用 curl
或 gRPC 客户端测试服务:
curl -X POST -d '{"name": "world"}' http://localhost:8000/helloworld.v1.Greeter/SayHello
9. 部署服务
- 使用 Docker 打包镜像:
kratos docker build
- 使用 Kubernetes 部署:
kratos k8s deploy
10. 其他功能
- 中间件:Kratos 支持中间件,可以在
internal/server/
中配置。 - 日志:Kratos 使用
log
包记录日志,支持多种日志级别。 - 监控:集成 Prometheus 和 OpenTelemetry 进行监控和追踪。