这是我参与「第五届青训营 」伴学笔记创作活动的第 11 天,本文主要以概括总结,全局记录为主,而不是作为细致的知识点讲解,细节之处多有疏忽还望多多包容。
一、本堂课重点内容:
- Kitex 介绍
二、详细知识点介绍:
安装 Kitex 代码生成工具
windows 下建议使用虚拟机或者 WSL2
go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
go intall github.com/cloudwego/thriftgo@latest
定义 IDL
//使用 IDL 定义服务与接口
namespce go api
struct Request{
1: string message
}
struct Response{
1: string message
}
service Echo{
Response echo(1: Request req)
}
如果我们要进行 RPC, 就需要知道对方的接口是什么,需要传什么参数,同时也需要知道返回值是什么样的。这时候,就需要通过 IDL,来约定双方的协议,就像在写代码的时候需要调用某个函数,我们需要知道函数签名一样。
使用 Kitex 生成代码
使用 Kitex-module example-service example echo.thrift 命令生成代码
build.sh:构建脚本 kitex_gen :IDL 内容相关的生成代码,主要是基础的 Server/Client 代码。 main.go 程序入口 handler.go 用户在该文件里实现 IDL service 定义的方法
Kitex 基本使用
服务器默认监听 8888 端口
package main
import(
"context"
"example/kitex_gen/api"
)
//EchoImpl implements the last service defined in the IDL.
type EchoImpl struct{}
//Echo implements the EchoImpl interfce.
fun (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.WithHostPort("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.WithRPCTimeout(3*time.Second))
if err != nil{
log.Fatal(err)
}
log.Println(resp)
Kitex 服务注册与发现
目前Kitex 的服务注册与发现已经对接了主流了服务注册于发现中心,如 ETCD, Nacos 等.
Kitex 生态
| XDS扩展 | github.com/kitex-contr… |
|---|---|
| opentelemetry 扩展 | github.com/kitex-contr… |
| EICD 服务注册与发现扩展 | github.com/kitex-contr… |
| Nacos 服务注册与发现扩展 | github.com/kitex-contr… |
| zookeeper 服务注册与发现扩展 | github.com/kitex-contr… |
| polaris 扩展 | github.com/kitex-contr… |
| 丰富的示例代码与业务Demo | github.com/cloudwego/k… |
三、课后个人总结:
kitex 作为优秀的 RPC 框架,是 Go 不可或缺的框架