1、簡介python
thrift是一個軟件框架,用來進行可擴展且跨語言的服務的開發。它結合了功能強大的軟件堆棧和代碼生成引擎,以構建在 C++, Java, Python, PHP, Ruby, Erlang, Perl, Haskell, C#, Cocoa, JavaScript, Node.js, Smalltalk, and OCaml 這些編程語言間無縫結合的、高效的服務。apache
2、安裝編程
1.下載地址 bash
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插件
app
pip install thrift
3、準備服務器端框架
1.編輯接口文件 helloworld.thrift:socket
service HelloWorld { string ping(), string say(1:string msg) }
2.編輯 server.py編程語言
#!/usr/bin/env python import socket import sys sys.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!"
4、準備客戶端ide
#!/usr/bin/env python import sys sys.path.append('./gen-py') from helloworld import HelloWorld #引入客戶端類 from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: #創建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)
ps:親測經過,吐槽一下,這東西之前都沒有據說過,就要拿來開發,還要只是用客戶端