Thrift的使用-Python
百科简介: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端输出: