【问题标题】:How to pass a thrift struct to Python Server如何将节俭结构传递给 Python 服务器
【发布时间】:2018-06-16 10:10:02
【问题描述】:

我正在使用 thrift 在 python 服务器和 java 客户端之间进行 rpc 通信。在我的节俭处理程序中,我有一个要传递节俭结构的函数。对于基本数据类型传递我可以直接做:

def assignValue(self, variable, value):

但现在我想传递结构而不是变量(字符串类型)。我该怎么做?

struct MyStruct { 1:string var1; 2:string var2; }

PS:我是thrift的新手,我正在关注thrift的官方documentation,如果有任何其他文档可以提供帮助,请随时传递。谢谢!

【问题讨论】:

    标签: python thrift


    【解决方案1】:

    这是一个在 Thrift IDL 中传递结构的简单示例:

    https://github.com/RandyAbernethy/ThriftBook/blob/master/part1/arch/halibut.thrift

    struct Date {
        1: i16  year
        2: i16  month
        3: i16  day
    }
    
    service HalibutTracking {
        i32 get_catch_in_pounds_today()
        i32 get_catch_in_pounds_by_date(1: Date dt, 2: double tm)
    }
    

    这里有一个 Java 客户端和服务器示例:

    https://github.com/RandyAbernethy/ThriftBook/tree/master/part3/ws/thrift

    它显示返回一个结构(但传递一个很容易推断)。 ThriftBook repo 中也有很多 Python 和 Java 的示例(全部来自 Programmer's Guide to Apache Thrift):

    示例 struct return thrift idl 如下所示:

    struct TradeReport {
        1: string  symbol,
        2: double  price,
        3: i32     size,
        4: i32     seq_num
    } 
    
    service TradeHistory {
        TradeReport get_last_sale(1: string Symbol) 
    }
    

    清单中的 Java 客户端如下所示:

    import java.io.IOException;
    import org.apache.thrift.TException;
    import org.apache.thrift.transport.TSocket;
    import org.apache.thrift.protocol.TBinaryProtocol;
    
    public class ThriftClient {
        public static void main(String[] args) 
                throws IOException, TException {
            TSocket trans = new TSocket("localhost", 9090);
            TBinaryProtocol proto = new TBinaryProtocol(trans);
            TradeHistory.Client client = new TradeHistory.Client(proto);
    
            trans.open();
            for (int i = 0; i < 1000000; i++) {
                TradeReport tr = client.get_last_sale("APPL");
            }
            trans.close();
        }
    }
    

    其他 IDL 示例在这里(包括几个传递结构的示例):

    https://github.com/RandyAbernethy/ThriftBook/tree/master/part2/IDL

    【讨论】:

    • 您能解释一下您的客户端 sn-p 中“TradeReport”类的定义方式和位置吗?
    • 完整项目在这里:github.com/RandyAbernethy/ThriftBook/tree/… TradeReport 类型在上面的 IDL 中定义。要为 Java 生成它,您可以使用 thrift 编译器和类似“$ thrift --gen java myidl.thrift”的命令
    猜你喜欢
    • 2020-09-11
    • 2017-01-02
    • 1970-01-01
    • 2011-08-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-20
    相关资源
    最近更新 更多