thrift在go中的初步使用

  1. 新建文件夹thrift-test,然后执行go mod init thrift-test初始化
  2. 在thrift-test根目录下新建文件: example.thrift 然后将下面代码粘进入
namespace go com.example   // 定义所使用的命名空间

struct Person {             // 定义一个结构体
  1: required string name,  // 姓名字段
  2: optional i32 age       // 年龄字段
}

service ExampleService {    // 定义一个服务接口
  void sayHello(1: string name) // sayHello方法,接收一个姓名参数
}
  1. 执行 go get github.com/apache/thrift/lib/go/thrift, 然后到go.mod中查看版本号,再去cmd执行thrift --version 查看thrift的版本号,如果相差很大就要降低thrift的版本,不然会报错,我这里都是thrift是0.18.0,而go-thrift是0.18.1,相差不大,则没有问题
  2. 执行thrift --gen go example.thrift 命令,会生成gen-go文件夹,点开看下,有可能导包错误,修改导包路径即可,如果不是导包路径的错误,则是thrift和go-thrift版本不对应的问题
  3. 新建service文件夹,在下面新建example_impl.go
package main

import (
	"context"
	"fmt"
)

type ExampleServiceImpl struct{}

func (e *ExampleServiceImpl) SayHello(ctx context.Context, name string) (err error) {
	fmt.Printf("Hello, %s!\n", name)
	return nil
}

然后在service文件夹下新建server.go

package main

import (
	"github.com/apache/thrift/lib/go/thrift"
	"thrift-test/gen-go/com/example"
)

func main() {
	handler := &ExampleServiceImpl{}
	processor := example.NewExampleServiceProcessor(handler)

	// 创建服务器传输对象
	transportFactory := thrift.NewTTransportFactory()
	confN := &thrift.TConfiguration{}
	protocolFactory := thrift.NewTBinaryProtocolFactoryConf(confN)
	serverTransport, err := thrift.NewTServerSocket(":9090")
	if err != nil {
		panic(err)
	}

	// 创建简单的单线程服务器
	server := thrift.NewTSimpleServer4(processor, serverTransport, transportFactory, protocolFactory)

	println("Starting the server...")
	server.Serve()
}

  1. 新建client文件夹,在client下新建client.go
package main

import (
	"context"
	"fmt"
	"github.com/apache/thrift/lib/go/thrift"
	"thrift-test/gen-go/com/example"
)

func main() {

	conf := &thrift.TConfiguration{}
	transport := thrift.NewTSocketConf("localhost:9090", conf)

	// 创建客户端协议
	confN := &thrift.TConfiguration{}
	protocolFactory := thrift.NewTBinaryProtocolFactoryConf(confN)
	client := example.NewExampleServiceClientFactory(transport, protocolFactory)

	// 打开连接
	if err := transport.Open(); err != nil {
		panic(err)
	}
	defer transport.Close()

	// 调用远程服务
	if err := client.SayHello(context.Background(), "world"); err != nil {
		panic(err)
	}
	fmt.Println("Done!")
}


  1. 然后分别运行服务端和客户端查看调用是否成功
  2. demo结构如下
    在这里插入图片描述
  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值