Python实现Thrift Server

近期在项目中存在跨编程语言协作的需求,使用到了Thrift。本文将记录用python实现Thrift服务端的方法。

环境准备

编写.thrift文件

.thrift文件定义了Thrift服务端和Thrift客户端的通信接口,在该文件中定义的接口需由服务端实现,并可被客户端调用。Thrift编译器会调用.thrift文件生成不同语言的thrift代码,用于之后实现thrift服务端或thrift客户端。

.thrift文件的编写规则可参考Thrift白皮书。下面将以demo.thrift文件举例

service DemoService{
    string ping(1:string param)
    map<i32,string> get_int_string_mapping_result(1:i32 key, 2:string value)
    bool get_bool_result()
}

在DemoService服务中分别定义了三个接口,说明了接口的入参与出参。

生成python对应的thrift代码

使用以下命令可以生成不同语言的thrift代码:

thrift --gen <language> <Thrift filename>

通过 thrift-0.9.3.exe --gen py demo.thrift 命令生成python版本的thrift文件,文件夹为gen-py,如下所示:

编写服务端

编写服务端server.py,用于实现在demo.thrift文件中定义的接口功能。

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
import sys

sys.path.append("./gen-py/")
from demo import DemoService
import random


class DemoServer:
    def __init__(self):
        self.log = {}

    def ping(self, param):
        return "echo:" + param

    def get_int_string_mapping_result(self, key, value):
        return {key: value}

    def get_bool_result(self):
        return random.choice([True, False])


if __name__ == '__main__':
    # 创建处理器
    handler = DemoServer()
    processor = DemoService.Processor(handler)

    # 监听端口
    transport = TSocket.TServerSocket(host="0.0.0.0", port=9999)

    # 选择传输层
    tfactory = TTransport.TBufferedTransportFactory()

    # 选择传输协议
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()

    # 创建服务端
    server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)

    # 设置连接线程池数量
    server.setNumThreads(5)

    # 启动服务
    server.serve()

编写客户端用于测试

编写客户端client.py,用于测试服务端功能是否可用。

from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol
import sys
sys.path.append("./gen-py/")

from demo import DemoService


if __name__ == '__main__':
    transport = TSocket.TSocket('127.0.0.1', 9999)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = DemoService.Client(protocol)

    # 连接服务端
    transport.open()

    recv = client.ping("test")
    print(recv)

    recv = client.get_int_string_mapping_result(10, "MyThrift")
    print(recv)

    recv = client.get_bool_result()
    print(recv)

    # 断连服务端
    transport.close()

编写完成后,整个项目结构如下图所示:

测试服务端

运行服务端server.py后,运行客户端client.py,打印的内容如下:

echo:test
{10: 'MyThrift'}
True

此时客户端能够正常调用服务端所提供的接口。(PS:在调试过程中,也许需要修改gen-py文件夹中Thrift编译器生成的python代码)

参考文档