Kitex与Hz上手配置 | 青训营笔记

312 阅读2分钟

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

当前[2023年1月15日]kitex对windows的支持依然不好,本文采用wsl2配置kitex,windows宿主配置hz的方式来进行开发环境的配置。

安装前的go环境配置

  1. go环境安装 此处不再赘述,参考之前的这篇文章:如何配置golang开发环境(详细) - 知乎 (zhihu.com)
  2. GOPATH设置 由于kitex和hz均提供脚手架工具,此类工具的可执行文件在userpath/go/bin下,所以需要配置好GOPATH,把GOPATH/bin写入PATH环境变量。GOPATH默认的地址为当前用户目录下的go文件夹。

windows下:

image.png

path环境变量中

image.png

wsl2 (linux)下: 在用户目录下编辑.bashrc

image.png

增加下面两行:

image.png

重启终端或者source .bashrc

安装hz

go install github.com/cloudwego/hertz/cmd/hz@latest

$ hz --version
hz version v0.5.0

安装kitex

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

$ kitex --version
vx.x.x

$ thriftgo --version
thriftgo x.x.x

使用hz和thriftgo

hz 命令行工具使用 | CloudWeGo

  1. 创建项目目录

mkdir learnhz

  1. 初始化hz项目

hz new --mod "learnhz"

  1. 拉取依赖

go mod tidy

thrift

  1. 创建idl文件
mkdir idl && touch idl/hello.thrift
  1. 写入内容
namespace go hello.example

struct HelloReq {
    1: string Name (api.query="name"); // 添加 api 注解为方便进行参数绑定
}

struct HelloResp {
    1: string RespBody;
}


service HelloService {
    HelloResp HelloMethod(1: HelloReq request) (api.get="/hello");
}
  1. 生成文件

hz new -idl idl/hello.thrift -module "learnhz"

go mod tidy

  1. 修改idl文件后更新项目

hz update -idl idl/hello.thrift

使用kitex和thriftgo

  1. 创建项目目录

mkdir learnkitex && cd learnkitex

  1. 编写idl文件
namespace go api

struct Request {
  1: string message
}

struct Response {
  1: string message
}

service Echo {
    Response echo(1: Request req)
}
  1. 生成server项目

kitex -module "learnkitex" -service "learnkitex" hello.thrift

  1. 注意,此处先go get github.com/cloudwego/kitex@latest && go mod tidy

  2. 修改handler,增加echo方法逻辑

  3. go mod tidy

  4. 运行编译脚本 sh build.sh

  5. 编译完成后,运行服务端:sh bootstrap.sh

  6. 生成client项目

mkdir client && cd client
touch main.go
package main

import (
	"context"
	"learnkitex/kitex_gen/api"
	"learnkitex/kitex_gen/api/echo"
	"log"
	"time"

	"github.com/cloudwego/kitex/client"
	"github.com/cloudwego/kitex/client/callopt"
)

func main() {
	c, err := echo.NewClient("example", client.WithHostPorts("0.0.0.0:8888")) //创建客户端
	if err != nil {
		log.Fatal(err)
	}

	req := &api.Request{Message: "teete"} // 构造request
	resp, err := c.Echo(context.Background(), req, callopt.WithRPCTimeout(3*time.Second)) // 调用Echo
	if err != nil {
		log.Fatal(err)
	}
	log.Println(resp)
}

go run main.go