python实现一个简单的thirft客户端和服务端

版权声明:旨在学习交流,共同进步 https://blog.csdn.net/u013735511/article/details/82655772

创建thrift文件

service Hello {
    string get()
}

使用thrift 创建服务需要的组件

thrift --gen py hello.thrift

得到一个gen-py文件,请将该文件放到新建的python项目下面

编写服务端

# coding=utf-8
from thrift_server.gen.hello.Hello import Processor
from thrift_server.gen.hello.ttypes import *
from thrift.Thrift import TType, TMessageType, TException
from thrift.Thrift import TProcessor
from thrift.transport import TSocket
from thrift.protocol import TBinaryProtocol, TProtocol
from thrift.server import TServer
import logging


class HelloHandler:
    def get(self):
        return "hello world"

def run():
    handler = HelloHandler()
    processor = Processor(handler)
    # 监听端口
    transport = TSocket.TServerSocket('localhost', 9234)
    # 选择传输层
    tfactory = TTransport.TBufferedTransportFactory()
    # 选择传输协议
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    # 创建服务端
    server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
    server.setNumThreads(5)
    logging.info('start thrift serve in python')
    server.serve()


if __name__ == '__main__':
    run()

编写客户端

from thrift_server.gen.hello.Hello import *
from thrift import Thrift
from thrift.transport import TSocket
from thrift.transport import TTransport
from thrift.protocol import TBinaryProtocol

try:
    transport = TSocket.TSocket('localhost', 9234)
    transport = TTransport.TBufferedTransport(transport)
    protocol = TBinaryProtocol.TBinaryProtocol(transport)
    client = Client(protocol)
    transport.open()

    print 'start'
    ret = client.get()
    print ret
    transport.close()
except Thrift.TException as e:
    print 'exception'
    print e

服务调用

首先启动服务端,再执行客户端,执行结果如下
这里写图片描述

注意事项

python需要安装thrift,如缺少其它组件,也可以类似安装

pip install thrift

猜你喜欢

转载自blog.csdn.net/u013735511/article/details/82655772