Python编程:实现消息发布/订阅模型

简介: Python编程:实现消息发布/订阅模型

基本模型:

发布者 -> 交换机 <-> 订阅者

代码示例

# -*- coding: utf-8 -*-


# 消息发布/订阅模型

from collections import defaultdict
from contextlib import contextmanager


class Exchange(object):
def __init__(self):
self._subscribers = set()

def attach(self, task):
self._subscribers.add(task)

def detach(self, task):
self._subscribers.remove(task)

def send(self, message):
for subscriber in self._subscribers:
subscriber.send(message)

@contextmanager
def subscribe(self, *tasks):
for task in tasks:
self.attach(task)
try:
yield
finally:
for task in tasks:
self.detach(task)


_exchanges = defaultdict(Exchange)


def get_exchange(name):
return _exchanges[name]


class Task(object):
def send(self, message):
"""发送消息的方法"""
print(message)


task1 = Task()
task2 = Task()


# 1、手动 添加注册,取消注册
exchage = get_exchange("message")
exchage.attach(task1)
exchage.attach(task2)

exchage = get_exchange("message")
exchage.send("你好")
# 你好
# 你好

exchage.detach(task1)
exchage.detach(task2)

# 2、使用上下文管理器

exchage = get_exchange("message")
with exchage.subscribe(task1, task2):
exchage.send("你好啊")

# 你好啊
# 你好啊

参考

12.11 实现消息发布/订阅模型

            </div>
目录
相关文章
|
28天前
|
API 开发工具 Python
【Azure Developer】Python 获取 Azure 中订阅(subscription)信息,包含ID, Name等
【Azure Developer】Python 获取 Azure 中订阅(subscription)信息,包含ID, Name等
|
28天前
|
开发工具 数据安全/隐私保护 Python
【Azure 环境】通过Python SDK收集所有订阅简略信息,例如订阅id 名称, 资源组及组内资源信息等,如何给Python应用赋予相应的权限才能获取到信息呢?
【Azure 环境】通过Python SDK收集所有订阅简略信息,例如订阅id 名称, 资源组及组内资源信息等,如何给Python应用赋予相应的权限才能获取到信息呢?
|
2月前
|
机器人 Shell 开发者
`roslibpy`是一个Python库,它允许非ROS(Robot Operating System)环境(如Web浏览器、移动应用等)与ROS环境进行交互。通过使用`roslibpy`,开发者可以编写Python代码来远程控制ROS节点,发布和订阅话题,以及调用服务。
`roslibpy`是一个Python库,它允许非ROS(Robot Operating System)环境(如Web浏览器、移动应用等)与ROS环境进行交互。通过使用`roslibpy`,开发者可以编写Python代码来远程控制ROS节点,发布和订阅话题,以及调用服务。
|
Python
Python实现因子分析(附案例实战)
Python实现因子分析(附案例实战)
1451 0
Python实现因子分析(附案例实战)
Python print() 打印两个 list ,实现中间换行
Python print() 打印两个 list ,实现中间换行
|
算法 大数据 Python
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
147 2
Leedcode 每日一练 搜索二维矩阵Ⅰ Python实现
|
存储 数据安全/隐私保护 计算机视觉
python 实现pacs功能 推送下拉影像
python 实现dcmtk关联pacs功能 推送下拉影像
263 0
python 实现pacs功能 推送下拉影像
|
前端开发 Python
Leecode加法题目3个 每日练习 Python实现
Leecode加法题目3个 每日练习 Python实现
106 0
Leecode加法题目3个 每日练习 Python实现
|
iOS开发 Python
Python实现微信消息连续发送
Python实现微信消息连续发送
Python实现微信消息连续发送
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”
python实现微信小游戏“飞机大战”