您的位置:首页 > 编程语言 > Python开发

thrift使用:java作为client端调用python服务端

2017-01-10 16:27 513 查看
摘要:使用pythonthriftserver,java客户端调用,并返回结果

一、环境准备

1、thrift安装:

windows环境下,只要到官网下载.exe文件到本地,然后将文件加入到path就可以使用了。

linux环境下,需要下载tar包,编译安装即可,至于编译安装的方法,我就不介绍了(有点懒)。

2、java和python依赖

java的maven依赖:

<!--thrift--> <dependency> <groupId>org.apache.thrift</groupId> <artifactId>libthrift</artifactId> <version>0.9.3</version> </dependency>
python中需要安装thrift模块,使用pip安装:pipinstallthrift

二、编写IDLthrift

新建一个hello.trift文件,内容如下:

serviceHello{

stringhelloString(1:stringword)

}

打开cmd,分别生成java和python代码

thrift--genpyhello.thrift在生成的gen-py/hello目录有如下文件



thrift--genjavahello.thrift生成如下代码



三、编写python服务端

注:这里需要将上面生成的python代码拷贝到你的项目里面,或者通过包引用的方式将目录添加进来,再引入到项目里面,java也是一样

HelloServer.py

fromhelloimportHello fromthrift.transportimportTSocket fromthrift.transportimportTTransport fromthrift.protocolimportTBinaryProtocol fromthrift.serverimportTServer classHelloHandler: def__init__(self): pass defhelloString(self,word): ret="Received:"+word returnret #handlerprocesser类 handler=HelloHandler() processor=Hello.Processor(handler) transport=TSocket.TServerSocket("127.0.0.1",8989) #传输方式,使用buffer tfactory=TTransport.TBufferedTransportFactory() #传输的数据类型:二进制 pfactory=TBinaryProtocol.TBinaryProtocolFactory() #创建一个thrift服务 server=TServer.TSimpleServer(processor,transport,tfactory,pfactory) print"Startingthriftserverinpython..." server.serve() print"done!"

四、编写java客户端

importcn.com.boanda.thrift.test.Hello;
importorg.apache.thrift.TException;
importorg.apache.thrift.protocol.TBinaryProtocol;
importorg.apache.thrift.protocol.TProtocol;
importorg.apache.thrift.transport.TSocket;
importorg.apache.thrift.transport.TTransport;
importorg.apache.thrift.transport.TTransportException;

/**
*@versionV0.1.0
*@Description:javathrift客户端
*@see
*@since2016-06-01
*/
publicclassThriftClient{
publicvoidstartClient(){
TTransporttransport;
try{
System.out.println("thriftclientconnextserverat8989port");
transport=newTSocket("127.0.0.1",8989);
TProtocolprotocol=newTBinaryProtocol(transport);
Hello.Clientclient=newHello.Client(protocol);
transport.open();
System.out.println(client.helloString("HelloThrift"));
transport.close();
System.out.println("thriftclientcloseconnextion");
}catch(TTransportExceptione){
e.printStackTrace();
}catch(TExceptione){
e.printStackTrace();
}
}

publicstaticvoidmain(String[]args){
System.out.println("thriftclientinit");
ThriftClientclient=newThriftClient();
System.out.println("thriftclientstart");
client.startClient();
System.out.println("thriftclientend");
}
}
五、运行

先启动python服务端,再启动java客户端,就可以看到结果了。至于thrift的介绍,后面我会继续写,或者大家可以参考网上的资料。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息