python专属的Remote Produce Call框架:rpyc

python专属的Remote Produce Call框架:rpyc

python生态里面的rpc框架很多,比较出名的有grpc和thrift,但是这两个框架在python体系里面用起来相对比较复杂,下面介绍一个极其简洁轻量级的纯python实现的RPC框架:rpyc。

rpyc开源地址github:

GitHub - tomerfiliba-org/rpyc: RPyC (Remote Python Call) - A transparent and symmetric RPC library for pythonRPyC (Remote Python Call) - A transparent and symmetric RPC library for python - GitHub - tomerfiliba-org/rpyc: RPyC (Remote Python Call) - A transparent and symmetric RPC library for pythonhttps://github.com/tomerfiliba-org/rpyc

(1)安装。

pip install rpyc

(2)编写RPC服务器端。

import sys
import time

import rpyc
from rpyc.utils.server import ThreadedServer


class MyRPCServer(rpyc.Service):
    def on_connect(self, conn):
        print(sys._getframe().f_code.co_name, sys._getframe().f_lineno, time.time())

    def on_disconnect(self, conn):
        print(sys._getframe().f_code.co_name, sys._getframe().f_lineno, time.time())

    def exposed_hello(self):
        print(sys._getframe().f_code.co_name, sys._getframe().f_lineno, time.time())
        return 'hello,world'

    def exposed_sum(self, a: int, b: int):
        print(a, b, sys._getframe().f_code.co_name, sys._getframe().f_lineno, time.time())
        return a + b

    exposed_constant_value = False


if __name__ == "__main__":
    t = ThreadedServer(MyRPCServer, port=9999)
    print('RPC服务器启动...')
    t.start()

    print(sys._getframe().f_code.co_name, sys._getframe().f_lineno, time.time())

(3)写一个简单RPC客户端。

import rpyc

if __name__ == "__main__":
    conn = rpyc.connect(host="127.0.0.1", port=9999)
    print(conn.root)
    print(conn.root.constant_value)
    print(conn.root.hello())
    print(conn.root.sum(1, 2))

(4)启动。

首先启动服务器端,然后启动客户端,依次启动后,RPC服务器端输出:

RPC服务器启动...
on_connect 10 1663145525.0500057
exposed_hello 16 1663145525.0519998
1 2 exposed_sum 20 1663145525.0530686
on_disconnect 13 1663145525.0571816

客户端输出:

<__main__.MyRPCServer object at 0x000001D789B98EE0>
False
hello,world
3

(5)总结。

rpyc框架体系中,服务器端定义的对外暴露的公开访问接口通过在方法前面加上 exposed_ 作为标识。在RPC服务器端定义的服务类,凡是以 exposed_ 开头的,均是客户端可以远程调用的接口,包括一些基础变量值。这很不同grpc的模式,grpc模式需要先定义RPC方法函数类文件。在rpyc不需要额外定义一个单独的文件,直接通过在代码文件中用exposed_标识即可,相当灵活简洁。

rpyc支持linux和Windows系统。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

zhangphil

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值