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