Python3实践thrift协议小实验

    xiaoxiao2025-03-29  13

    首先需要thrift编译器,thrift-0.12.0.exe,APache官网可以下载,不过网络不好的话可以用百度云的文件:

    链接:https://pan.baidu.com/s/1uF32l-zqP6VWFGy0zuGRhA  提取码:xba4   

    接下来,自己写个简单的thrift协议,保存为hello.thrift文件如下

    /* thrift接口定义文件 say接口接收一个参数msg,返回数值类型 body接口接收3个参数,返回字符串类型 */ service HelloService { i32 say( 1:string msg); string body( 1:i32 id 2:string name 3:i32 age) }

    然后使用thrift分别生成Python代码:在cmd输入如下命令

    thrift-0.12.0.exe --gen py hello.thrift

    则会生成如下文件夹gen-py:

    进入gen-py目录:

    新建服务端Python代码, service.py:

    # coding: utf-8 from hello import HelloService from hello.ttypes import * from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer class HelloServiceHandler: def say(self, msg): ret = "服务端接收到的信息为:" + msg print (ret) return len(msg) # 返回int,与thrift文件中定义的返回i32数据类型一致 def body(self, id, name, age): return f'id是{id}, 姓名是{name}, 年龄是{age}' # 返回string,与thrift文件中一致 handler = HelloServiceHandler() processor = HelloService.Processor(handler) # 定义一个TProcess处理类,创建TProcess对象 transport = TSocket.TServerSocket("localhost", 9090) # 设置网络读写 tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() server = TServer.TSimpleServer(processor, transport, tfactory, pfactory) print("启动服务") server.serve()

    编写客户端Python代码,client.py:

    # coding: utf-8 from hello import HelloService from thrift import Thrift from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol while True: try: transport = TSocket.TSocket('localhost', 9090) # 创建一个传输层对象(TTransport),设置调用的服务地址为本地,端口为 9090,TSocket传输方式 transport = TTransport.TBufferedTransport(transport) protocol = TBinaryProtocol.TBinaryProtocol(transport) # 创建通信协议对象(TProtocol),设置传输协议为 TBinaryProtocol client = HelloService.Client(protocol) # 创建一个Thrift客户端对象 transport.open() send_msg = input("客户端发送信息:") rec_msg = client.say(send_msg) print("say方法返回的信息为:" , rec_msg) rec_msg = client.body(2, send_msg, 28) print('body方法返回的信息为:', rec_msg) except Thrift.TException as ex: print(ex.message) finally: transport.close()

    然后分别用2个cmd窗口,先运行服务端代码,再运行客户端代码,效果如下:

    最新回复(0)