mprpc 是一个超快速的Python RPC 库,最近一直在看 RPC 的东西,考虑如何应用到公司的项目中,模仿 Celery 的方式二次封装了一下。python
项目地址: mprpc_configgit
pip install mprpc_config
构建一个以下的目录结构github
config.py 包含RPC配置属性(任意命名)shell
app_module_name RPC 接口模块(任意命名,可有多个)服务器
server.py RPC 服务器app
Configration
类,将 config.py
的模块名 config
做为字符串传入bind_class
方法将初始化后的全部 RPC 接口绑定给 RPCServer
客户端启动方式可参考 mprpc 。函数
示例代码在
example
目录
server.py测试
from mprpc_config.rpc_server import RPCServer, StreamServer from mprpc_config import rpc_config if __name__ == '__main__': print('-------start server--------') config = rpc_config.Configuration("config") config.bind_class(RPCServer) server = StreamServer(('127.0.0.1', 6000), RPCServer) server.serve_forever(stop_timeout=10)
client.pycode
from mprpc_config.rpc_client import RPCClient, RPCPoolClient from mprpc_config.rpc_client import RPCPool print('---------- client ----------') client = RPCClient('127.0.0.1', 6000) print('2 add 4: ', client.call('add', 2, 4)) print('2 plus 4: ', client.call('plus', 2, 4)) print('2 minus 4: ', client.call('minus', 2, 4)) print('---------- done ----------') print('---------- client pool ----------') client_pool = RPCPool(RPCPoolClient, dict(host='127.0.0.1', port=6000)) with client_pool.connection() as client: print('2 add 4: ', client.call('add', 2, 4)) print('2 plus 4: ', client.call('plus', 2, 4)) print('2 minus 4: ', client.call('minus', 2, 4)) print('---------- done ----------')
启动 server 和 clientserver
$ python server.py ---------- server ---------- $ python client.py ---------- client ---------- 2 add 4: 6 2 plus 4: 8 2 minus 4: -2 ---------- done ---------- ---------- client pool ---------- 2 add 4: 6 2 plus 4: 8 2 minus 4: -2 ---------- done ----------