优化Thrift客户端代码:分离连接、协议和调用
在Thrift客户端开发中,每个方法都重复定义socket连接、传输协议等,导致代码冗余且难以维护。本文介绍一种更优雅的方案:将连接、协议和方法调用分离。
通过创建辅助函数,例如fundinfoserviceclient,实现连接和协议层的初始化,并返回fundinfo.fundinfoserviceclient对象和thrift.ttransport对象。
func fundinfoserviceclient(ip, port string) (*fundinfo.fundinfoserviceclient, thrift.ttransport, error) { transportFactory := thrift.NewTFramedTransportFactory(thrift.NewTTransportFactory()) protocolFactory := thrift.NewTBinaryProtocolFactoryDefault() transport, err := thrift.NewTSocket(net.JoinHostPort(ip, port)) if err != nil { return nil, nil, fmt.Errorf("无法解析地址: %w", err) } tTransport := transportFactory.GetTransport(transport) client := fundinfo.NewFundInfoServiceClientFactory(tTransport, protocolFactory) if err := tTransport.Open(); err != nil { return nil, nil, fmt.Errorf("无法连接到 %s:%s: %w", ip, port, err) } return client, tTransport, nil}
登录后复制
在实际调用方法时,只需调用fundinfoserviceclient获取客户端对象和传输对象,然后执行方法调用,并记得关闭连接。
func processFundInfo(ctx context.Context, fundcode string, ip, port string) (*fundinfo.FundInfo, error) { client, tTransport, err := fundinfoserviceclient(ip, port) if err != nil { return nil, err } defer tTransport.Close() res, err := client.GetFundInfo(ctx, fundcode) if err != nil { return nil, fmt.Errorf("调用GetFundInfo失败: %w", err) } return res, nil}
登录后复制
这种方法显著提升了代码的可读性和可维护性。 调用不同服务端方法时,只需创建相应的辅助函数即可,避免了重复代码。 错误处理也更加清晰。
以上就是如何高效地分离Thrift客户端的连接、协议和调用?的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2308672.html