Thrift 是一种接口描述语言和二进制通讯协议。之前也没接触过,最近有个项目须要创建自动化测试,这个项目之间的微服务都是经过 Thrift 进行通讯的,而后写自动化脚本以前研究了一下。python
须要定义一个xxx.thrift的文件, 来生成各类语言的代码,生成以后咱们的服务提供者和消费者,都须要把代码引入,服务端把代码实现,消费者直接使用API的存根,直接调用。apache
和 http 相比,同属于应用层,走 tcp 协议。Thrift 优点在于发送一样的数据,request包 和 response包 要比 http 小不少,在总体性能上要优于 http 。json
环境准备:windows
1.首先使用 thrift 以前须要定义一个 .thrift 格式的文件,好比 test.thrift服务器
service Transmit { string sayMsg(1:string msg); string invoke(1:i32 cmd 2:string token 3:string data) }
而后运行命令:thrift-0.9.3.exe -gen py test.thrift 生成 python 代码socket
生成以下结构
tcp
2.而后将生成的 python 代码 和 文件,放到新建的 python 项目中。完成后先运行服务器代码。ide
import json from test import Transmit from test.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 TransmitHandler: def __init__(self): self.log = {} def sayMsg(self, msg): msg = json.loads(msg) print("sayMsg(" + msg + ")") return "say " + msg + " from " + socket.gethostbyname(socket.gethostname()) def invoke(self,cmd,token,data): cmd = cmd token =token data = data if cmd ==1: return json.dumps({token:data}) else: return 'cmd不匹配' if __name__=="__main__": handler = TransmitHandler() processor = Transmit.Processor(handler) transport = TSocket.TServerSocket('127.0.0.1', 8000) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print("Starting python server...") server.serve()
import sys import jsonfrom test import Transmit from test.ttypes import * from test.constants import * from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol transport = TSocket.TSocket('127.0.0.1', 8000) transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Transmit.Client(protocol) # Connect! transport.open() cmd = 2 token = '1111-2222-3333-4444' data = json.dumps({"name":"zhoujielun"}) msg = client.invoke(cmd,token,data) print(msg) transport.close() # 执行结果:cmd不匹配