1月29日Go学习笔记|青训营笔记

116 阅读2分钟

这是我参与【第五届青训营】伴学笔记创作活动的第七天

安装Kitex代码生成工具

在终端中输入 go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
或 go install github.com/cloudwego/thriftgo@latest kitex -version可以查看版本

定义IDL

使用IDL定义服务与接口 如果我们要进行RPC,就需要知道对方的接口,需要传什么参数,同时也要知道返回值是什么样的,这时候就要通过IDL来约定双方的协议。具体如下所示:

namespcae go api

struct Request{
	1: string message
}
struct Response{
	2: string message
}
service Echo{
	Response echo(1: Request req)
}

Kitex生成代码

//命令生成代码
kitex -module example -service example echo.thirft 


语法:`kitex [options] IDL`

下面以 thrift IDL 作为例子。 Protobuf IDL 的使用也是类似的。

#### 生成客户端代码[](https://www.cloudwego.io/zh/docs/kitex/tutorials/code-gen/code_generation/#%E7%94%9F%E6%88%90%E5%AE%A2%E6%88%B7%E7%AB%AF%E4%BB%A3%E7%A0%81)

kitex path_to_your_idl.thrift


执行后在当前目录下会生成一个名为 kitex_gen 目录,其中包含了 IDL 定义的数据结构,以及与 IDL 里定义的 service 相对应的 `*service` 包,提供了创建这些 serviceclient API。

#### 生成服务端代码[](https://www.cloudwego.io/zh/docs/kitex/tutorials/code-gen/code_generation/#%E7%94%9F%E6%88%90%E6%9C%8D%E5%8A%A1%E7%AB%AF%E4%BB%A3%E7%A0%81)

kitex -service service_name path_to_your_idl.thrift


执行后在当前目录下会生成一个名为 kitex_gen 目录,同时包含一些用于创建和运行一个服务的脚手架代码。具体见[生成代码的结构](https://www.cloudwego.io/zh/docs/kitex/tutorials/code-gen/code_generation/#%E7%94%9F%E6%88%90%E4%BB%A3%E7%A0%81%E7%9A%84%E7%BB%93%E6%9E%84)一节的描述。

### 生成代码的结构[](https://www.cloudwego.io/zh/docs/kitex/tutorials/code-gen/code_generation/#%E7%94%9F%E6%88%90%E4%BB%A3%E7%A0%81%E7%9A%84%E7%BB%93%E6%9E%84)

假设我们有两个 thrift IDL 文件,demo.thrift 和 base.thrift,其中 demo.thrift 依赖了 base.thrift,并且 demo.thrift 里定义了一个名为 `demo` 的 service 而 base 里没有 service 定义。

那么在一个空目录下,`kitex -service demo demo.thrift` 生成的结果如下:

`
 build.sh                     // 服务的构建脚本,会创建一个名为 output 的目录并生成启动服务所需的文件到里面
 handler.go                   // 用户在该文件里实现 IDL service 定义的方法
 kitex_gen                    // IDL 内容相关的生成代码
 base                     // base.thrift 的生成代码
 base.go              // thriftgo 的产物,包含 base.thrift 定义的内容的 go 代码
 k-base.go            // kitex 在 thriftgo 的产物之外生成的代码
 demo                     // demo.thrift 的生成代码
 demo.go              // thriftgo 的产物,包含 demo.thrift 定义的内容的 go 代码
 k-demo.go            // kitex 在 thriftgo 的产物之外生成的代码
 demoservice          // kitex 为 demo.thrift 里定义的 demo service 生成的代码
 demoservice.go   // 提供了 client.go 和 server.go 共用的一些定义
 client.go        // 提供了 NewClient API
 server.go        // 提供了 NewServer API
 main.go                      // 程序入口
 script                       // 构建脚本
 bootstrap.sh             // 服务的启动脚本,会被 build.sh 拷贝至 output 下


如果不指定 `-service` 参数,那么生成的只有 kitex_gen 目录。