echo.thrift:
namespace go echostruct EchoReq {1: string msg;
}struct EchoRes {1: string msg;
}service Echo {EchoRes echo(1: EchoReq req);
}
如果是Win10的话直接下载执行exe,其它系统可能需要先安装thrift 0.14.1,下载地址/
thrift-0. -r --gen go echo.thrift
生成目录gen-go结构如下:
.
├──
├── echo.thrift
├── gen-go
│ └── echo
│ ├──
│ ├──
│ ├── echo-remote
│ │ └──
│ └── GoUnusedProtection__.go
├── go.mod
├── go.sum
└──
module thrift-examplego 1.13require github/apache/thrift v0.14.1
示例代码里和之前的版本不同的有两点:
1)引用路径现在是”github/apache/thrift/lib/go/thrift“
2)函数的声明和调用增加了context.Context参数
package mainimport ("context""fmt""github/apache/thrift/lib/go/thrift""thrift-example/gen-go/echo"
)type EchoServer struct {
}func (e *EchoServer) Echo(ctx context.Context, req *echo.EchoReq) (*echo.EchoRes, error) {fmt.Printf("message from client: %vn", req.GetMsg())res := &echo.EchoRes{Msg: "success",}return res, nil
}func main() {transport, err := thrift.NewTServerSocket(":9898")if err != nil {panic(err)}handler := &EchoServer{}processor := echo.NewEchoProcessor(handler)transportFactory := thrift.NewTBufferedTransportFactory(8192)//也可以选择Framed传输协议,但是必须确保服务端和客户端的传输协议一致//transportFactory := thrift.NewTBufferedTransportFactory(8192)//framedtransportFactory := thrift.NewTFramedTransportFactory(transportFactory)//可以选择任意一种编码协议,但是必须确保服务端和客户端的编码协议一致protocolFactory := thrift.NewTBinaryProtocolFactory(true, true) //布尔参数strictRead, strictWrite,读和写时是否加入版本校验。//protocolFactory := thrift.NewTCompactProtocolFactory()//protocolFactory := thrift.NewTJSONProtocolFactory()server := thrift.NewTSimpleServer4(processor,transport,transportFactory,protocolFactory,)if err := server.Serve(); err != nil {panic(err)}
}
<
package mainimport ("context""fmt""github/apache/thrift/lib/go/thrift""log""net""os""thrift-example/gen-go/echo"
)func main() {transportFactory := thrift.NewTBufferedTransportFactory(8192)//可以选择任意一种通信协议,但是必须确保服务端和客户端的通信协议一致protocolFactory := thrift.NewTBinaryProtocolFactory(true, true) //布尔参数strictRead, strictWrite,读和写时是否加入版本校验。//protocolFactory := thrift.NewTCompactProtocolFactory()//protocolFactory := thrift.NewTJSONProtocolFactory()transport, err := thrift.NewTSocket(net.JoinHostPort("127.0.0.1", "9898"))if err != nil {fmt.Fprintln(os.Stderr, "error resolving address:", err)os.Exit(1)}useTransport, err := transportFactory.GetTransport(transport)client := echo.NewEchoClientFactory(useTransport, protocolFactory)if err := transport.Open(); err != nil {fmt.Fprintln(os.Stderr, "Error opening socket to 127.0.0.1:9898", " ", err)os.Exit(1)}defer transport.Close()req := &echo.EchoReq{Msg: "You are welcome."}res, err := client.Echo(context.Background(), req)if err != nil {log.Println("Echo failed:", err)return}log.Println("response:", res.Msg)fmt.Println("well done")}
测试使用的Go版本go1.13.8
相关文章:
《thrift协议0.14.1在Nodejs和Go语言之间的跨语言调用的兼容性测试》
参考文章:
《Go thrift使用举例》
本文发布于:2024-02-02 22:48:57,感谢您对本站的认可!
本文链接:https://www.4u4v.net/it/170688533546960.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
留言与评论(共有 0 条评论) |