Kitex学习 | 青训营笔记

227 阅读2分钟

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

教程:www.cloudwego.io/zh/docs/kit…

Kitex 是一个 RPC 框架,既然是 RPC,底层就需要两大功能:

  • Serialization 序列化
  • Transport 传输

Kitex 框架及命令行工具,默认支持 thrift 和 proto3 两种 IDL,对应的 Kitex 支持 thrift 和 protobuf 两种序列化协议。传输上 Kitex 使用扩展的 thrift 作为底层的传输协议(注:thrift 既是 IDL 格式,同时也是序列化协议和传输协议)。IDL 全称是 Interface Definition Language,接口定义语言。

为什么要使用 IDL

如果我们要进行 RPC,就需要知道对方的接口是什么,需要传什么参数,同时也需要知道返回值是什么样的,就好比两个人之间交流,需要保证在说的是同一个语言、同一件事。这时候,就需要通过 IDL 来约定双方的协议,就像在写代码的时候需要调用某个函数,我们需要知道函数签名一样。

Thrift IDL 语法可参考:thrift.apache.org/docs/idl

proto3 语法可参考:developers.google.com/protocol-bu…

使用

  1. 安装

安装 kitex:

go install github.com/cloudwego/kitex/tool/cmd/kitex@latest

安装 thriftgo:

go install github.com/cloudwego/thriftgo@latest
  1. 编写IDL

创建一个名为 xxx.thrift 的 thrift IDL 文件,在里面定义我们的服务

namespace go api

struct Request {
  1: string message
}

struct Response {
  1: string message
}

service Echo {
    Response echo(1: Request req)
}
  1. 生成 echo 服务代码
kitex -module example -service example echo.thrift
  • -module 表示生成的该项目的 go module 名

  • -service 表明我们要生成一个服务端项目

  • example 为该服务的名字

  • 最后一个参数则为该服务的 IDL 文件

  1. 编写服务端

需要编写的服务端逻辑都在 handler.go 文件中

package main

import (
  "context"
  "example/kitex_gen/api"
)

// EchoImpl implements the last service interface defined in the IDL.
type EchoImpl struct{}

// Echo implements the EchoImpl interface.
func (s *EchoImpl) Echo(ctx context.Context, req *api.Request) (resp *api.Response, err error) {
  // TODO: Your code here...
  return
}
  1. 编写客户端
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)
}
  1. 调用
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)
  1. 运行
sh build.sh
sh output/bootstrap.sh

生态