这是我参与「第五届青训营 」笔记创作活动的第5天
kitex是一个Golang微服务的RPC框架,具有高可用性、强扩展性。
IDL
Interface Definition Language 接口定义语言。kitex默认支持thrift和proto3两种IDL,对应thrift和protobuf两种序列化协议。 Kitex目前不支持Windows,本地环境Windows的可以使用虚拟机或者是WSL2
快速上手
我是在WSL中操作。 在应用商店搜索ubuntu,选择一个版本下载(安装教程www.jianshu.com/p/3e627ff45…
安装完毕后,输入
wsl -l -v
正常显示WSL版本号信息
然后输入wsl进入linux系统
安装Golang,可自行搜索linux安装golang。
go环境安装好后,安装kitex和thrift
go install github.com/cloudwego/kitex/tool/cmd/kitex@latest
go install github.com/cloudwego/thriftgo@latest
打开goland,克隆demo到wsl的文件夹下
直接在goland中运行main.go或者打开terminal执行
cd hello
go run .
即启动一个服务
然后运行client下的main.go,或者新开启一个terminal窗口,执行
go run ./client
则成功发起一个rpc调用
项目内容
首先是IDL定义,即
thrift.go
namespace go api
//请求格式
struct Request {
1: string message
}
//返回格式
struct Response {
1: string message
}
//请求方法名
service Hello {
Response echo(1: Request req)
}
main.go
func main() {
svr := api.NewServer(new(HelloImpl))
err := svr.Run()
if err != nil {
log.Println(err.Error())
}
}
handler.go
// HelloImpl实现了在IDL中定义的服务接口
type HelloImpl struct{}
// Echo方法实现了HelloImpl接口.
func (s *HelloImpl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) {
// TODO: 请求处理
resp = &api.Response{Message: req.Message}
return
}
kitex_gen
kitex_gen中是kitex根据IDL生成的代码文件。 通过命令
kitex -module "your_module_name" -service a.b.c hello.thrift
更新代码文件。执行完毕,将更新handler.go文件和kitex_gen文件夹下的文件。
新增代码
在hello.thrift文件中新增一个方法及其对应的请求体格式和返回格式
然后执行命令更新代码
kitex -service a.b.c hello.thrift
# 若当前目录不在 $GOPATH/src 下,需要加上 -module 参数,一般为 go.mod 下的名字
kitex -module "your_module_name" -service a.b.c hello.thrift
打开go.mod文件即为module名
此时.handler和kitex_gen文件进行了更新
.handler新增了一个add方法
修改业务逻辑
func (s *HelloImpl) Add(ctx context.Context, req *api.AddRequest) (resp *api.AddResponse, err error) {
resp := &api.AddResponse(Sum: req.First + req.Second)
return
}
在client/main.go新增调用
重新运行后,我们就发起了一个新的RPC调用
参考:www.cloudwego.io/zh/docs/kit…