这是我参与「第五届青训营」伴学笔记创作活动的第 8 天
Go框架三件套详解 —— Kitex
安装Kitex代码生成工具
Kitex目前对Windows的支持不完善,如果本地开发环境是Windows的同学建议使用虚拟机或WSL2。
安装代码生成工具
go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
go install gihub.com/cloudwego/thriftgo@latest
定义IDL
使用IDL定义服务于接口
如果我们要进行RPC,就需要知道对方的接口是什么,需要传什么参数,同时也需要知道返回值是什么样的。这时候,就需要通过IDL来约定双方的协议,就像在写代码的时候需要调用某个函数,我们需要知道函数签名一样。
什么是IDL
接口描述语言(Interface definition language, IDL)是一种语言的通用术语,它允许用一种语言编写的程序与另一种语言编写的程序通信。我们通过IDL来支持RPC的信息传输定义。Kitex支持thrift和proto3两种IDL。
namespace go api
struct Request {
1: string message
}
struct Response {
1: string message
}
service Echo {
Response echo(1: Request req)
}
使用Kitex生成代码
使用kitex -module example -service example echo.thrift命令生成代码
- build.sh:构建脚本
- kitex_gen:IDL内容相关的生成代码,主要是基础的Server/Client代码
- main.go 程序入口
- handler.go 用户在该文件里实现IDL service定义的方法
Kitex基本使用
服务默认监听8080端口
pacakge main
import (
"context"
"example/kitex_gen/api"
)
// EchoImpl implements the last service interface difined in the IDL
type EchoImpl struct{}
func (s *EchoImpl) Echo(ctx context.Context, req *api.Request)(resp *api.Response, err error) {
// TODO: Your code here...
return
}
Kitex Client 发起请求
创建Client
import "example/kitex_gen/api/echo"
import "github.com/cloudwego/kitex/client"
...
c, err := echo.NewClient("example", client.WithHostPorts("0.0.0.0:8888"))
if err != nil {
log.Fatal(err)
}
发起请求
import "example/kitex_gen/api"
...
req := &api.Request{Message: "my request"}
resp, err := c.Echo(context.Background(), req, callopt.WihtRPCTimeout(3*time.Second))
if err != nil {
log.Fatal(err)
}
log.Println(resp)
服务注册与发现
目前Kitex的服务注册与发现已经对接了服务注册与发现中心,如ETCD,Nacos等。