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

本文详细介绍了如何使用Python实现一个简单的Thrift客户端和服务端。从创建Thrift文件开始,接着生成服务所需组件,然后分别编写服务端和客户端代码,并进行服务调用。在操作过程中需要注意先启动服务端再执行客户端,确保所有依赖组件已正确安装。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

创建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
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值