vlambda博客
学习文章列表

thrift实现跨语言的调用

笔者在工作中有这么一个应用场景:使用python调用java的服务,客户端是:python;服务器端是:java

具体要怎么做呢?

一,对python而言

0,准备好 thrift 文件,shared.thrift(namespace py shared ,这句话很关键),tutorial.thrift(同样,namespace py tutorial 这句话很关键);


1,thrift --gen py tutorial.thrift


2,thrift --gen py shared.thrift


最终会生成一个文件夹:gen-py,ta下面有shared,tutorial


shared(constants.py,ttypes.py,SharedService.py)


tutorial(Calculator.py,constants.py,ttypes.py)


二,对java而言

0,准备好 thrift 文件,shared.thrift(namespace java shared ,这句话很关键),tutorial.thrift(同样,namespace java tutorial 这句话很关键);


1,thrift --gen java tutorial.thrift


2,thrift --gen java shared.thrift


最终会生成一个文件夹:gen-java,ta下面有shared,tutorial


shared(SharedService.java,SharedStruct.java)


tutorial(Calculator.java,tutorialConstants.java,InvalidOperation.java,Work.java,Operation.java)


三,服务端源码:

package statMetricsToGra.thrift;


import org.apache.thrift.server.TServer;

import org.apache.thrift.server.TSimpleServer;

import org.apache.thrift.transport.TServerSocket;

import org.apache.thrift.transport.TServerTransport;


public class JavaServer {

    private static CalculatorHandler handler;


    private static Calculator.Processor processor;


    public static void main(String[] args) {

        try {

            handler = new CalculatorHandler();

            processor = new Calculator.Processor(handler);

            Runnable simple = new Runnable() {

                public void run() {

                    simple(processor);

                }

            };

            new Thread(simple).start();

        } catch (Exception x) {

            x.printStackTrace();

        }

    }


    private static void simple(Calculator.Processor processor) {

        try {

            TServerTransport serverTransport = new TServerSocket(9090);

            TServer server = new TSimpleServer(new TServer.Args(serverTransport).processor(processor));

            System.out.println("Starting the simple server...");

            server.serve();

        } catch (Exception e) {

            e.printStackTrace();

        }

    }

}


四,客户端源码

import Calculator

from ttypes import InvalidOperation, Operation, Work


from thrift import Thrift


from thrift.transport import TSocket


from thrift.transport import TTransport


from thrift.protocol import TBinaryProtocol



def main():

    transport = TSocket.TSocket('localhost', 9090)

    transport = TTransport.TBufferedTransport(transport)

    protocol = TBinaryProtocol.TBinaryProtocol(transport)

    client = Calculator.Client(protocol)

    transport.open()


    client.ping()

    print('ping()')


    sum_ = client.add(1, 1)

    print('1+1=%d' % sum_)

    work = Work()

    work.op = Operation.DIVIDE

    transport.close()



if __name__ == '__main__':

    try:

        main()

    except Thrift.TException as tx:

        print('%s' % tx.message)