百科簡介:Thrift是一種接口描述語言和二進制通訊協議,它被用來定義和創建跨語言的服務。它被當作一個遠程過程調用(RPC)框架來使用,是由Facebook為“大規模跨語言服務開發”而開發的。它通過一個代碼生成引擎聯合了一個軟件棧,來創建不同程度的、無縫的跨平台高效服務,可以使用C#、C++(基於POSIX兼容系統)、Cappuccino、Cocoa、Delphi、Erlang、Go、Haskell、Java、Node.js、OCaml、Perl、PHP、Python、Ruby和Smalltalk。雖然它以前是由Facebook開發的,但它現在是Apache軟件基金會的開源項目了。該實現被描述在2007年4月的一篇由Facebook發表的技術論文中,該論文現由Apache掌管。
thrift主頁:http://thrift.apache.org
thrift下載:thrift-0.12.0.tar.gz 解壓安裝不多說^_^ (Mac用戶直接使用$ brew install thrift 安裝即可)
在python程序中使用thrift需要安裝thrift模塊,pip install thrift 即可
thrift 采用IDL(Interface Definition Language)來定義通用的服務接口,並通過生成不同的語言代理實現來達到跨語言、平台的功能。在thrift的IDL中可以定義以下一些類型:基本數據類型,結構體,容器,異常、服務。
const string HELLO_MAN = "man" service HelloWorld { void ping(), string sayHello(), string sayMsg(1:string msg) }
thrift腳本通過Thrift編譯器生成所要求的python開發語言代碼。即:
thrift -r --gen py helloworld.thrift
執行后生成的文件目錄
Thrift是一個典型的CS結構,客戶端和服務端可以使用不同的語言開發,本文以python為例:
PythonServer.py
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 import socket class HelloWorldHandler: def __init__(self): self.log = {} def ping(self): print("ping()") def sayHello(self): print("sayHello()") return "say hello from " + socket.gethostbyname(socket.gethostname()) def sayMsg(self, msg): print("sayMsg(" + msg + ")") return "say " + msg + " from " + socket.gethostbyname(socket.gethostname()) handler = HelloWorldHandler() processor = HelloWorld.Processor(handler) transport = TSocket.TServerSocket('127.0.0.1', 30303) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print("Starting python server...") server.serve() print("done!")
PythonClient.py
import sys sys.path.append('./gen-py') from helloworld import HelloWorld from helloworld.ttypes import * from helloworld.constants import * from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol try: # Make socket transport = TSocket.TSocket('127.0.0.1', 30303) # Buffering is critical. Raw sockets are very slow transport = TTransport.TBufferedTransport(transport) # Wrap in a protocol protocol = TBinaryProtocol.TBinaryProtocol(transport) # Create a client to use the protocol encoder client = HelloWorld.Client(protocol) # Connect! transport.open() client.ping() print("ping()") msg = client.sayHello() print(msg) msg = client.sayMsg(HELLO_MAN) print(msg) transport.close() except Thrift.TException as tx: print(tx.message)
server端輸出:
client端輸出: