优化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客户端的连接、协议和调用?的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号