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的介紹,後面我會繼續寫,或者你們能夠參考網上的資料。

相關文章
相關標籤/搜索