Thrift 是一款高性能、开源的 RPC 框架,产自 Facebook 后贡献给了 Apache,Thrift 囊括了整个 RPC 的上下游体系,自带序列化编译工具,由于 Thrift 采用的是二进制序列化,而且与 gRPC 同样使用的都是长链接创建 client 与 server 之间的通信,相比于比传统的使用XML,JSON,SOAP等短链接的解决方案性能要快得多。
本篇只介绍 Python 关于 Thrift 的基础使用。python
- 经过 pip 命令安装,缺点必需要有外网或者内网的 pip 源:$ pip install thrift
直接下载:thrift complier 下载地址,下载完成后更名为:thrift.exe 并将其放入到系统环境变量下便可使用git
从 github 上下载 thrift 0.10.0 的源码,解压后进入:thrift-0.10.0/compiler/cpp 目录执行以下命令完成编译后,将其放入到系统环境变量下便可使用:
$ mkdir cmake-build
$ cd cmake-build
$ cmake ..
$ makegithub
$ thrift -version,若是打印出来:Thrift version 0.10.0 代表 complier 安装成功apache
下面咱们使用 Thrift 定义一个接口,该接口实现对传入的数据进行大写的格式化处理。windows
- client目录下的 client.py 实现了客户端用于发送数据并打印接收到 server 端处理后的数据
example.thrift:app
namespace py example struct Data { 1: string text } service format_data { Data do_format(1:Data data), }
进入 thrift_file 目录执行:$ thrift -out .. --gen py example.thrift,就会在 thrift_file 的同级目录下生成 python 的包:example框架
server.py:socket
#! /usr/bin/env python # -*- coding: utf-8 -*- __author__ = 'xieyanke' from example import format_data from example import ttypes from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from thrift.server import TServer __HOST = 'localhost' __PORT = 8080 class FormatDataHandler(object): def do_format(self, data): return ttypes.Data(data.text.upper()) if __name__ == '__main__': handler = FormatDataHandler() processor = format_data.Processor(handler) transport = TSocket.TServerSocket(__HOST, __PORT) tfactory = TTransport.TBufferedTransportFactory() pfactory = TBinaryProtocol.TBinaryProtocolFactory() rpcServer = TServer.TSimpleServer(processor,transport, tfactory, pfactory) print('Starting the rpc server at', __HOST,':', __PORT) rpcServer.serve()
client.py:工具
#! /usr/bin/env python # -*- coding: utf-8 -*- from thrift.transport import TSocket from thrift.transport import TTransport from thrift.protocol import TBinaryProtocol from example.format_data import Client from example.format_data import Data __HOST = 'localhost' __PORT = 8080 tsocket = TSocket.TSocket(__HOST, __PORT) transport = TTransport.TBufferedTransport(tsocket) protocol = TBinaryProtocol.TBinaryProtocol(transport) client = Client(protocol) data = Data('hello,world!') transport.open() print(client.do_format(data).text)
- 先启动 server,以后再执行 client