一、前言:
Thrift 是一种接口描述语言和二进制通信协议。以前也没接触过,最近有个项目需要建立自动化测试,这个项目之间的微服务都是通过 Thrift 进行通信的,然后写自动化脚本之前研究了一下。
需要定义一个xxx.thrift的文件, 来生成各种语言的代码,生成之后我们的服务提供者和消费者,都需要把代码引入,服务端把代码实现,消费者直接使用API的存根,直接调用。
和 http 相比,同属于应用层,走 tcp 协议。Thrift 优势在于发送同样的数据,request包 和 response包 要比 http 小很多,在整体性能上要优于 http 。
二、使用方法
环境准备:
从官网上下载 windows 版的 thrift.exe:http://archive.apache.org/dist/thrift/0.9.3/ (我这里用的是0.9.3版本)
python版本:Python 3.7.1
pip3 install thrift
1.首先使用 thrift 之前需要定义一个 .thrift 格式的文件,比如 test.thrift
service Transmit {
string sayMsg(1:string msg);
string invoke(1:i32 cmd 2:string token 3:string data)
}
View Code
然后运行命令:thrift-0.9.3.exe -gen py test.thrift 生成 python 代码
生成如下结构
2.然后将生成的 python 代码 和 文件,放到新建的 python 项目中。完成后先运行服务器代码。
服务端代码 server.py:
importjsonfrom test importTransmitfrom test.ttypes import *
from thrift.transport importTSocketfrom thrift.transport importTTransportfrom thrift.protocol importTBinaryProtocolfrom thrift.server importTServerimportsocketclassTransmitHandler:def __init__(self):
self.log={}defsayMsg(self, msg):
msg=json.loads(msg)print("sayMsg(" + msg + ")")return "say" + msg + "from" +socket.gethostbyname(socket.gethostname())definvoke(self,cmd,token,data):
cmd=cmd
token=token
data=dataif cmd ==1:returnjson.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()
客户端代码 client.py
importsysimportjsonfrom test importTransmitfrom test.ttypes import *
from test.constants import *
from thrift importThriftfrom thrift.transport importTSocketfrom thrift.transport importTTransportfrom thrift.protocol importTBinaryProtocol
transport= TSocket.TSocket('127.0.0.1', 8000)
transport=TTransport.TBufferedTransport(transport)
protocol=TBinaryProtocol.TBinaryProtocol(transport)
client=Transmit.Client(protocol)#Connect!
transport.open()
cmd= 2token= '1111-2222-3333-4444'data= json.dumps({"name":"zhoujielun"})
msg=client.invoke(cmd,token,data)print(msg)
transport.close()#执行结果:
cmd不匹配
本文介绍了Thrift作为接口描述语言和二进制通信协议在微服务自动化测试中的应用。通过创建xxx.thrift文件定义服务接口,然后使用thrift工具生成Python代码,分别用于服务端和客户端。Thrift相较于HTTP,其请求和响应包更小,性能更优。文中提供了服务端(server.py)和客户端(client.py)的Python代码示例,展示了如何通过Thrift进行通信。
9420

被折叠的 条评论
为什么被折叠?



