win7+thrift+python的一个RPC例子的实现

Thrift Python RPC 实战
本文详细介绍如何在Python环境中安装配置Thrift,并通过一个Hello World示例,展示Thrift的编译过程及服务端与客户端的实现代码。从环境搭建到代码运行,全程实战讲解。

一 安装环境

1 python安装thrift包

    pip install thrift

2 下载win版本的“thrift-0.11.0.exe”

    http://thrift.apache.org/download

3 安装pychar的thrift插件,用于提高编写thrift的自动补全

    https://plugins.jetbrains.com/plugin/7331-thrift-support

    把下载的“intellij-thrift.zip”解压出来之后的.jar文件拷贝到pycharm安装目录下的lib目录下。

 

二 实现一个hello的例子

1 定义hello.thrift

 

2 用thrift编译器编译(使用了Cygwin64 Terminal)

$ ./thrift-0.11.0.exe -r -gen py hello.thrift

这样就生成了py的代码了,在"gen-py"。这个包可以被后面自己写的服务端和客户端代码使用。

3 建立python的工程

    用pycharm建立工程"thrift_hello"工程,然后把上一步生成的软件包拷贝到这个工程目录下。工程目录如下。因为python中,包的路径好像不支持'-',因此要把“gen-py”重命名成'gen_py'。

4 编写客户端和服务端的实现代码。

hello_server.py

 

from gen_py.hello import Hello
from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport

__HOST = '127.0.0.1'
__PORT = 9090


class hello_handle:
    def helloString(self, para):
        print(para)
        return "result:" + para
if __name__ == '__main__':
    # 创建服务端
    handler = hello_handle()
    processor = Hello.Processor(handler)
    # 监听端口
    transport = TSocket.TServerSocket(host=__HOST, port=__PORT)
    # 选择传输层
    tfactory = TTransport.TBufferedTransportFactory()
    # 选择传输协议
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    # 创建服务端
    server = TServer.TThreadPoolServer(processor, transport, tfactory, pfactory)
    server.setNumThreads(5)

    print('Starting the server')
    server.serve()
    print('done')

hello_client.py

 

from gen_py.hello import Hello


from thrift.Thrift import TException
from thrift.protocol import TBinaryProtocol
from thrift.protocol import TProtocol
from thrift.transport import TSocket, TTransport

__HOST = '127.0.0.1'
__PORT = 9090

if __name__ == '__main__':
    try:
        print('客户端启动....')

        transport = TSocket.TSocket(host=__HOST, port=__PORT)
        transport = TTransport.TBufferedTransport(transport)
        protocol = TBinaryProtocol.TBinaryProtocol(transport)
        client =  Hello.Client(protocol)
        transport.open()
        result = client.helloString("hello")
        print(result)
        transport.close()

        print('done')
    except TException as e:
        print(e)

 

 

5 运行代码

   1 先运行hello_server

    2 运行hello_client输出结果:

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值