Go thrift 使用

1,464 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第8天,点击查看活动详情

Thrift 是啥?

Thrift是一套包含序列化功能和支持服务通信的RPC框架,主要包含三大部分:代码生成、序列化框架、RPC框架,大致相当于protoc + protobuffer + grpc,并且支持大量语言,保证常用功能在跨语言间功能一致,是一套全栈式的RPC解决方案。Thrift最初由FaceBook开发,之后由ASF管理。

Thrift 整体架构

在这里插入图片描述

请求响应模型

在这里插入图片描述### 安装 Thrift 的 Golang 库

go get git.apache.org/thrift.git/lib/go/thrift

安装 Thrift IDL 的编译工具

thrift-0.10.0.exe 和go get 版本不一致会导致 to many errors 错误

直接下载:thrift complier 下载地址,下载完成后改名为:thrift.exe 并将其放入到系统环境变量下即可使用 在这里插入图片描述 在这里插入图片描述 在这里插入图片描述

编译 thrift 文件

进入 thrift_file 目录执行:$ thrift -out .. --gen go example.thrift,就会在 thrift_file 的同级目录下生成 golang 的包:example,其中 format_data-remote 是生成的测试代码可以不用特别关注

thrift -r --gen go example.thrift

在这里插入图片描述

代码

/** thrift_example.go */
package main

import (
	"GoProject/src/thrift/gen-go/example"
	"context"
	"fmt"
	"github.com/apache/thrift/lib/go/thrift"
	"log"
	"net"
	"os"
)

const (
	HOST = "localhost"
	PORT = "19090"
)

type TransdataImpl struct {
}

func (trandata *TransdataImpl) SendMsg(ctx context.Context, msgJson string) (r bool, err error) {
	fmt.Println("-->SendMsg Call:", msgJson)
	return true, nil
}

func Server() {
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
	//protocolFactory := thrift.NewTCompactProtocolFactory()

	serverTransport, err := thrift.NewTServerSocket(net.JoinHostPort(HOST, PORT))
	if err != nil {
		fmt.Println("Error!", err)
		os.Exit(1)
	}

	handler := &TransdataImpl{}
	processor := example.NewTransdataProcessor(handler)

	server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)
	fmt.Println("thrift server in", net.JoinHostPort(HOST, PORT))
	server.Serve()
}

func Client() {
	tSocket, err := thrift.NewTSocket(net.JoinHostPort(HOST, PORT))
	if err != nil {
		log.Fatalln("tSocket error:", err)
	}
	transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory())
	transport, _ := transportFactory.GetTransport(tSocket)
	protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()

	client := example.NewTransdataClientFactory(transport, protocolFactory)

	if err := transport.Open(); err != nil {
		log.Fatalln("Error opening:", HOST+":"+PORT)
	}
	defer transport.Close()

	d, err := client.SendMsg(nil, "test string")
	fmt.Println(d)
}

测试代码

/** thrift_example_test.go */
package main

import (
	"testing"
)

func TestServer(t *testing.T) {
	Server()
}

func TestClient(t *testing.T) {
	Client()
}

参考资料