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

 

1、环境准备html

一、thrift安装:java

windows环境下,只要到官网下载.exe文件到本地,而后将文件加入到path就能够使用了。python

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

二、java和python依赖web

java的maven依赖:apache

<!--thrift-->
<dependency>
    <groupId>org.apache.thrift</groupId>
    <artifactId>libthrift</artifactId>
    <version>0.9.3</version>
</dependency>

python中须要安装thrift模块,使用pip安装:pip install thriftwindows

2、编写IDL thriftmaven

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

service Hello {    server

    string helloString(1:string word)    

}  

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

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

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

3、编写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!"
 

4、编写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 ");
}
}

5、运行

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

相关文章
相关标签/搜索