发布一个基于 mprpc_config 二次封装的 pip 包

mprpc 是一个超快速的Python RPC 库,最近一直在看 RPC 的东西,考虑如何应用到公司的项目中,模仿 Celery 的方式二次封装了一下。

项目地址: mprpc_config

安装

pip install mprpc_config

用法

构建一个如下的目录结构

  • config.py 包含RPC配置属性(任意命名)

    • INSTALLED_APP 必填参数,list 类型,将每一个包含 RPC 接口的模块名放进去
  • app_module_name RPC 接口模块(任意命名,可有多个)

    • implement.py 接口模块(任意命名,可有多个),里面包含 rpc 方法装饰的接口函数
  • server.py RPC 服务器

    1. 初始化 mprpc_config 的 Configration 类,将 config.py 的模块名 config 作为字符串传入
    2. 导入 mprpc_config.rpc_server 的 RPCServer 和 StreamServer,启动 RPC 服务器
    3. 使用 bind_class 方法将初始化后的所有 RPC 接口绑定给 RPCServer
    4. 使用 StreamServer 启动 RPC 服务器
  • client.py RPC 客户端(测试用,实际可分离)

    客户端启动方式可参考 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.py

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 和 client

$ 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 ----------

原文:发布一个基于 mprpc_config 二次封装的 pip 包
博客:时空路由器

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,845评论 18 139
  • 关于Mongodb的全面总结 MongoDB的内部构造《MongoDB The Definitive Guide》...
    中v中阅读 32,008评论 2 89
  • 转自:http://blog.csdn.net/kesonyk/article/details/50924489 ...
    晴天哥_王志阅读 24,903评论 2 38
  • 当夏日的喧嚣已被褪去、火辣的太阳收起起那侵略性的目光的时候,夏夜已经悄然来临。人们开始慢慢地睡去,家家户户的灯光也...
    小小寻阅读 545评论 8 6
  • 早上起来,惯性打开喜马拉雅,听张德芬老师的课程,突然心情大好。立刻把昨天的悲伤情绪拉回来,我和我自己在一起,...
    朱雨哲阅读 144评论 0 0