- 新建文件夹thrift-test,然后执行go mod init thrift-test初始化
- 在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方法,接收一个姓名参数
}
- 执行 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,相差不大,则没有问题
- 执行thrift --gen go example.thrift 命令,会生成gen-go文件夹,点开看下,有可能导包错误,修改导包路径即可,如果不是导包路径的错误,则是thrift和go-thrift版本不对应的问题
- 新建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()
}
- 新建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!")
}
- 然后分别运行服务端和客户端查看调用是否成功
- demo结构如下