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

一、环境准备

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安装:pip install thrift

二、编写IDL thrift

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

service Hello {

string helloString(1:string word)

}

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

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

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

thrift --gen java hello.thrift 生成如下代码

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

三、编写python服务端

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

HelloServer.py

from hello import Hello
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
class HelloHandler:
def __init__(self):
pass
 def helloString(self, word):
 ret = "Received: " + word
return ret
#handler processer类
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 "Starting thrift server in python..."
server.serve()
print "done!"

四、编写java客户端

import cn.com.boanda.thrift.test.Hello;
import org.apache.thrift.TException;
import org.apache.thrift.protocol.TBinaryProtocol;
import org.apache.thrift.protocol.TProtocol;
import org.apache.thrift.transport.TSocket;
import org.apache.thrift.transport.TTransport;
import org.apache.thrift.transport.TTransportException;
/**
 * @version V0.1.0
 * @Description: java thrift 客户端
 * @see
* @since 2016-06-01
 */
public class ThriftClient {
public void startClient() {
 TTransport transport;
 try {
 System.out.println("thrift client connext server at 8989 port ");
transport = new TSocket("127.0.0.1", 8989);
TProtocol protocol = new TBinaryProtocol(transport);
Hello.Client client = new Hello.Client(protocol);
transport.open();
System.out.println(client.helloString("Hello Thrift"));
transport.close();
System.out.println("thrift client close connextion");
} catch (TTransportException e) {
 e.printStackTrace();
} catch (TException e) {
 e.printStackTrace();
}
 }
public static void main(String[] args) {
 System.out.println("thrift client init ");
ThriftClient client = new ThriftClient();
System.out.println("thrift client start ");
client.startClient();
System.out.println("thrift client end ");
}
}

五、运行

先启动python服务端,再启动java客户端,就可以看到结果了。至于thrift的介绍,后面我会继续写,或者大家可以参考网上的资料。

作者:ivan-Zhao

原文:https://my.oschina.net/u/780876/blog/691293

相关推荐