参考(
golang客户端,服务端编写示例
逍遥子曰的thrift专题
)
第一步:编写 thrift 文件
定义 命名空间,数据结构,服务接口
- 数据结构并非一定要定义,但在实际项目中一般会将需要的数据做封装,即定义数据结构
#命名空间
namespace go rpc
# 服务接口
service hello {
string helloString(1:i64 uid)
}
thrift 工具生成代码,如下
- hello-remote.go 为生成的用于测试的客户端,可以做参考
检查各个文件有没有错误,因为有时生产环境比较复杂,生成的文件要做一次检查
// 编写服务端代码
type RpcHello struct{}
// thrift文件定义中只有1个返回值,但这里要2个返回值
func (r RpcHello) HelloString(ctx context.Context, id int64) (string, error) {
str := fmt.Sprintf("hello world_id=%d", id)
return str, nil
}
func main() {
addr := "127.0.0.1:8080"
// 服务处理
handler := RpcHello{}
processor := rpc.NewHelloProcessor(handler)
// 网络传输方式:客户端与服务端需一致
serverTransport, err := thrift.NewTServerSocket(addr)
if err != nil {
panic(err)
}
//TBinaryProtocol传输格式,客户端与服务端需一致
server := thrift.NewTSimpleServer2(processor, serverTransport)
fmt.Println("start server")
server.Serve()
}
//编写客户端代码
func main() {
addr := "127.0.0.1:8080"
var transport thrift.TTransport
var err error
// 网络传输方式:需要与服务端一致
transport, err = thrift.NewTSocket(addr)
defer transport.Close()
if err != nil {
panic(err)
}
err = transport.Open()
if err != nil {
panic(err)
}
defer transport.Close()
// 传输协议:需要与服务端一致
protocolFactory := thrift.NewTBinaryProtocolFactoryDefault()
iProtocol := protocolFactory.GetProtocol(transport)
oProtocol := protocolFactory.GetProtocol(transport)
tClient := thrift.NewTStandardClient(iProtocol, oProtocol)
// 实际业务
ctx := context.Background()
cli := rpc.NewHelloClient(tClient)
rs, _ := cli.HelloString(ctx, 100)
fmt.Println(rs)
}
####运行服务端
####运行客户端