thrift 最初是 facebook 开发使用的 rpc 通信框架,后来贡献给了 apache 基金会,出来得比较早,几乎支持所有的后端语言,使用非常广泛,是不可不知的一个网络框架
和 grpc 一样,需要先定义通信协议,然后实现自己业务逻辑,下面还是通过一个简单示例(之前的echo程序)说明 thrift 的用法,下面示例使用的完整代码在下列地址:
实现文件:https://github.com/hatlonely/...
协议文件:https://github.com/hatlonely/...
go get git.apache.org/thrift.git/lib/go定义协议文件
namespace go echostruct EchoReq { 1: string msg;}struct EchoRes { 1: string msg;}service Echo { EchoRes echo(1: EchoReq req);}
执行 thrift -r --gen go echo.thrift
命令会生成 gen-go
文件夹,这个过程其实是将上面的协议翻译成 golang 代码
这个命令依赖于 thrift 工具,可以通过下面命令获取
Mac
brew install thrift
linux
wget http://www-us.apache.org/dist/thrift/0.11.0/thrift-0.11.0.tar.gztar -xzvf thrift-0.11.0.tar.gzcd thrift-0.11.0./configuremake -j8[sudo] make install实现服务端
type EchoServerImp struct {}func (e *EchoServerImp) Echo(ctx context.Context,req *echo.EchoReq) (*echo.EchoRes,error) { fmt.Printf("message from clIEnt: %v\n",req.GetMsg()) res := &echo.EchoRes{ Msg: req.GetMsg(),} return res,nil}func main() { transport,err := thrift.NewTServerSocket(":3000") if err != nil { panic(err) } processor := echo.NewEchoProcessor(&EchoServerImp{}) server := thrift.NewTSimpleServer4( processor,transport,thrift.NewTBufferedTransportFactory(8192),thrift.NewTCompactProtocolFactory(),) if err := server.Serve(); err != nil { panic(err) }}
这个过程和 grpc 类似,不同的地方在于,thrift 支持更多的服务器类型,支持不同的协议打包方式,方便用户选择,这里的 compact 协议是一种压缩的协议,使用比较多
实现客户端func main() { var transport thrift.TTransport var err error transport,err = thrift.NewTSocket("localhost:3000") if err != nil { fmt.Errorf("NewTSocket Failed. err: [%v]\n",err) return } transport,err = thrift.NewTBufferedTransportFactory(8192).GetTransport(transport) if err != nil { fmt.Errorf("NewTransport Failed. err: [%v]\n",err) return } defer transport.Close() if err := transport.open(); err != nil { fmt.Errorf("Transport.Open Failed. err: [%v]\n",err) return } protocolFactory := thrift.NewTCompactProtocolFactory() iprot := protocolFactory.GetProtocol(transport) oprot := protocolFactory.GetProtocol(transport) clIEnt := echo.NewEchoClIEnt(thrift.NewTStandardClIEnt(iprot,oprot)) var res *echo.EchoRes res,err = clIEnt.Echo(context.Background(),&echo.EchoReq{ Msg: strings.Join(os.Args[1:]," "),}) if err != nil { fmt.Errorf("clIEnt echo Failed. err: [%v]",err) return } fmt.Printf("message from server: %v",res.GetMsg())}
这个 clIEnt 相对复杂一些,需要和 server 端设置一致的打包方式,如果不一致会出现通信失败,这一点需要特别注意一下
参考链接 thrift go 官网: http://thrift.apache.org/tuto... thrift github: https://github.com/apache/thr... thrift go tutorial: https://github.com/apache/thr...转载请注明出处总结
本文链接: http://hatlonely.github.io/20...
以上是内存溢出为你收集整理的golang 网络框架之 thrift全部内容,希望文章能够帮你解决golang 网络框架之 thrift所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)