Kitex+Hertz的练习(二) | 青训营笔记

122 阅读2分钟

这是我参与「第五届青训营 」笔记创作活动的第6天

把上次没写完的练习写完,上篇文章见 Kitex+Hertz的练习 | 青训营笔记

一、本文内容:

二、详细介绍

Hertz的简单流程

首先进入hertz-demo文件夹,准备基于 thrift IDL 创建项目。

cd hertz-demo

接口描述语言(Interface definition language,IDL) 是一种语言的通用术语,它允许用一种语言编写的程序或对象与用未知语言编写的另一个程序进行通信。 我们可以使用 IDL 来支持 RPC 的信息传输定义。Kitex 默认支持 thrift 和 proto3 两种 IDL。

Thrift IDL 语法可参考:Thrift interface description language

proto3 语法可参考:Language Guide(proto3)

要使用 thrift 或 protobuf 的 IDL 生成代码,需要安装相应的编译器:thriftgoprotoc

hz 生成的代码里,一部分是底层的编译器生成的(通常是关于 IDL 里定义的结构体),另一部分是 IDL 中用户定义的路由、method 等信息。用户可直接运行该代码。

从执行流上来说,当 hz 使用 thrift IDL 生成代码时,hz 会调用 thriftgo 来生成 go 结构体代码,并将自身作为 thriftgo 的一个插件(名为 thrift-gen-hertz)来执行来生成其他代码。当用于 protobuf IDL 时亦是如此。

此次我们使用thrift来定义IDL。新建文件idl/hello.thrift,并下如下代码:

// idl/hello.thrift
namespace go hello.example

struct HelloReq {
    1: string Name (api.query="name"); // 添加 api 注解为方便进行参数绑定
}

struct HelloResp {
    1: string RespBody;
}


service HelloService {
    HelloResp HelloMethod(1: HelloReq request) (api.get="/hello");
}

接下来,使用以下指令基于上述idl文件生成代码:

hz new -mod kitex-hertz-demo/hertz-demo -idl idl/hello.thrift
go mod tidy

上述命令中,-mod 表示生成的该项目的 go module 名,-idl 表明我们要基于idl生成代码,最后一个参数为该服务的 IDL 文件。生成后的项目结构如下: .

├── biz

│ ├── handler

│ │ ├── hello

│ │ │ └── example

│ │ │ └── hello_service.go

│ │ └── ping.go

│ ├── model

│ │ └── hello

│ │ └── example

│ │ └── hello.go

│ └── router

│ ├── hello

│ │ └── example

│ │ ├── hello.go

│ │ └── middleware.go

│ └── register.go

├── go.mod

├── go.sum

├── idl

│ └── hello.thrift

├── main.go

├── router_gen.go

└── router.go

11 directories, 12 files

接下来修改 handler,添加自己的逻辑。

handler path: biz/handler/hello/example/hello_service.go

其中 "hello/example" 是 thrift idl 的 namespace。

"hello_service.go" 是 thrift idl 中 service 的名字,所有 service 定义的方法都会生成在这个文件中。

我们为自己的项目添加自己的逻辑,这里我选择对名字打招呼,然后输出当前时间。

resp.RespBody = "hello," + req.Name + ", it is " + time.Now().String() // 添加的逻辑

使用go build命令构建可执行文件hertz-demo,然后执行可执行文件hertz-demo

测试:

curl --location --request GET 'http://127.0.0.1:8888/hello?name=LSJ'

可见可以正常收到回复{"RespBody":"hello,LSJ, it is 2023-01-29 17:28:40.631967901 +0800 CST m=+87.108378011"}

本文如有不足之处,欢迎大家指出