python事件总线
pyeventbus的Python项目详细描述
PyEventBus是Python2.7的发布/订阅事件总线。
- 简化了python类之间的通信
- 分离事件发送方和接收方
- 执行良好的线程、greenlet、队列和并发进程
- 避免复杂且易出错的依赖关系和生命周期问题
- 使代码更简单
- 具有高级功能,如传送线程、工作线程和生成不同进程等。
- 很小(3KB存档)
PyEventBus分3步:
定义事件:
class MessageEvent: # Additional fields and methods if needed def __init__(self): pass
准备订阅服务器:声明并注释订阅方法,或者指定线程模式:
from pyeventbus import * @subscribe(onEvent=MessageEvent) def func(self, event): # Do something pass
注册您的订户。例如,如果要在python中注册类:
from pyeventbus import * class MyClass: def __init__(self): pass def register(self, myclass): PyBus.Instance().register(myclass, self.__class__.__name__) # then during initilization myclass = MyClass() myclass.register(myclass)
发布事件:
from pyeventbus import * class MyClass: def __init__(self): pass def register(self, myclass): PyBus.Instance().register(myclass, self.__class__.__name__) def postingAnEvent(self): PyBus.Instance().post(MessageEvent()) myclass = MyClass() myclass.register(myclass) myclass.post()
模式:PyEventBus可以在5种不同模式下运行订阅方法
发布:
Runs the method in the same thread as posted. For example, if an event is posted from main thread, the subscribing method also runs in the main thread. If an event is posted in a seperate thread, the subscribing method runs in the same seperate method This is the default mode, if no mode has been provided:: @subscribe(threadMode = Mode.POSTING, onEvent=MessageEvent) def func(self, event): # Do something pass
绿色:
Runs the method in a greenlet using gevent library:: @subscribe(threadMode = Mode.GREENLET, onEvent=MessageEvent) def func(self, event): # Do something pass
背景:
Adds the subscribing methods to a queue which is executed by workers:: @subscribe(threadMode = Mode.BACKGROUND, onEvent=MessageEvent) def func(self, event): # Do something pass
Runs the method in a seperate python thread:: @subscribe(threadMode = Mode.PARALLEL, onEvent=MessageEvent) def func(self, event): # Do something pass
并发:
Runs the method in a seperate python process:: @subscribe(threadMode = Mode.CONCURRENT, onEvent=MessageEvent) def func(self, event): # Do something pass
将PyEventBus添加到项目:
pip install pyeventbus
示例:
git clone https://github.com/n89nanda/pyeventbus.git cd pyeventbus virtualenv venv source venv/bin/activate pip install pyeventbus python example.py
基准和性能:
Refer /pyeventbus/tests/benchmarks.txt for performance benchmarks on CPU, I/O and networks heavy tasks. Run /pyeventbus/tests/test.sh to generate the same benchmarks.
灵感
Inspired by Eventbus from greenrobot: https://github.com/greenrobot/EventBus