Thrift的服务器和客户端Python案例

2021-10-09 15:52:52 浏览数 (1)

服务器

Thrift提供的常见服务端类型有一下几种:

  • thrift.server.TServer.TSimpleServer 单线程服务器
  • thrift.server.TServer.TThreadedServer 多线程服务器
  • thrift.server.TServer.TThreadPoolServer 线程池服务器
  • thrift.server.TServer.TForkingServer 多进程服务器

我们以线程池服务器为例,其他方式相同。

代码语言:javascript复制
import sys
sys.path.append('gen-py')  # 增加生成代码的查找包路径

from calculate import Calculate
from base.ttypes import InvalidOperation, Operation

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol
from thrift.server import TServer


class CalculateHandler(Calculate.Iface):
    """被调用方法的具体实现"""
    def ping(self):
        print('ping()')

    def divide(self, num1, num2):
        if num2 == 0:
            raise InvalidOperation(0, 'Cannot divide by 0')
        return num1 / num2

    def calculate(self, work):
        if work.op == Operation.ADD:
            val = work.num1   work.num2
        elif work.op == Operation.SUBTRACT:
            val = work.num1 - work.num2
        elif work.op == Operation.MULTIPLY:
            val = work.num1 * work.num2
        else:
            raise InvalidOperation(work.op, 'Invalid operation')
        return val


if __name__ == '__main__':
    handler = CalculateHandler()
    processor = Calculate.Processor(handler)
    transport = TSocket.TServerSocket(host='127.0.0.1', port=8888)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TCompactProtocol.TCompactProtocolFactory()

    server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
    server.serve()
    print('服务器已启动')

客户端

代码语言:javascript复制
import sys
sys.path.append('gen-py')

from calculate import Calculate
from base.ttypes import InvalidOperation, Operation, Work

from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TCompactProtocol


def main():
    transport = TSocket.TSocket('127.0.0.1', 8888)

    # 使用缓存传输
    transport = TTransport.TBufferedTransport(transport)

    # 使用压缩的二进制消息协议
    protocol = TCompactProtocol.TCompactProtocol(transport)

    client = Calculate.Client(protocol)

    # 连接
    transport.open()

    client.ping()
    print('ping()')

    result = client.divide(100, 50)
    print('100/50={}'.format(result))

    try:
        result = client.divide(100, 0)
    except InvalidOperation as e:
        print(e.why)

    work = Work(1, 2, Operation.ADD)
    result = client.calculate(work)
    print('1 2={}'.format(result))

    work = Work(15, 10, Operation.SUBTRACT)
    result = client.calculate(work)
    print('15-10={}'.format(result))

    # 关闭
    transport.close()


if __name__ == '__main__':
    main()

0 人点赞