本文生動簡潔介紹了如何通過python搭建一個服務端和客戶端的簡單測試程序。
一、簡介
thrift是一個軟件框架,用來進行可擴展且跨語言的服務的開發。它結合了功能強大的軟件堆棧和代碼生成引擎,以構建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 這些編程語言間無縫結合的、高效的服務。
二、安裝
1.下載地址
http://www.apache.org/dyn/closer.cgi?path=/thrift/0.9.2/thrift-0.9.2.tar.gz
2.安裝
[root@localhost ~]# yum -y groupinstall "Development Tools"[root@localhost ~]# yum -y install libevent-devel zlib-devel openssl-devel autoconf automake[root@localhost ~]# wget http://ftp.gnu.org/gnu/bison/bison-2.5.1.tar.gz [root@localhost ~]# tar xf bison-2.5.1.tar.gz[root@localhost ~]# cd bison-2.5.1[root@localhost ~]# ./configure --prefix=/usr[root@localhost ~]# make[root@localhost ~]# make install[root@localhost ~]# tar xf thrift-0.9.2.tar.gz [root@localhost ~]# cd thrift-0.9.2[root@localhost thrift-0.9.2]# ./configure -with-lua=no
3.安裝python插件
pip install thrift
三、準備服務器端
1.編輯接口文件helloworld.thrift:
#!/usr/bin/env python import socketimport syssys.path.append('./gen-py') from helloworld import HelloWorld from helloworld.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer class HelloWorldHandler: def ping(self): return "pong" def say(self, msg): ret = "Received: " + msg print ret return ret#創建服務端handler = HelloWorldHandler()processor = HelloWorld.Processor(handler)#監聽端口transport = TSocket.TServerSocket("localhost", 9090)#選擇傳輸層tfactory = TTransport.TBufferedTransportFactory()#選擇傳輸協議pfactory = TBinaryProtocol.TBinaryProtocolFactory()#創建服務端 server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print "Starting thrift server in python..."server.serve()print "done!"四、準備客戶端
#!/usr/bin/env pythonimport syssys.path.append('./gen-py')from helloworld import HelloWorld #引入客戶端類from thrift import Thrift from thrift.transport import TSocketfrom thrift.transport import TTransportfrom thrift.protocol import TBinaryProtocoltry: #建立socket transport = TSocket.TSocket('localhost', 9090) #選擇傳輸層,這塊要和服務端的設置一致 transport = TTransport.TBufferedTransport(transport) #選擇傳輸協議,這個也要和服務端保持一致,否則無法通信 protocol = TBinaryProtocol.TBinaryProtocol(transport) #創建客戶端 client = HelloWorld.Client(protocol) transport.open() print "client - ping" print "server - " + client.ping() print "client - say" msg = client.say("Hello!") print "server - " + msg #關閉傳輸 transport.close()#捕獲異常except Thrift.TException, ex: print "%s" % (ex.message)
新聞熱點
疑難解答