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>
目录
相关文章
|
3天前
|
数据挖掘 索引 Python
Python数据挖掘编程基础3
字典在数学上是一个映射,类似列表但使用自定义键而非数字索引,键在整个字典中必须唯一。可以通过直接赋值、`dict`函数或`dict.fromkeys`创建字典,并通过键访问元素。集合是一种不重复且无序的数据结构,可通过花括号或`set`函数创建,支持并集、交集、差集和对称差集等运算。
14 9
|
3天前
|
前端开发 Python
Python编程的面向对象(二)—类的多态
Python编程的面向对象(二)—类的多态
12 7
|
2天前
|
存储 开发者 Python
探索Python编程的奥秘
【9月更文挑战第29天】本文将带你走进Python的世界,通过深入浅出的方式,解析Python编程的基本概念和核心特性。我们将一起探讨变量、数据类型、控制结构、函数等基础知识,并通过实际代码示例,让你更好地理解和掌握Python编程。无论你是编程新手,还是有一定基础的开发者,都能在这篇文章中找到新的启示和收获。让我们一起探索Python编程的奥秘,开启编程之旅吧!
|
3天前
|
人工智能 小程序 API
文字转语音神器+Python编程搞定语音报时小程序
文字转语音神器+Python编程搞定语音报时小程序
10 2
|
3天前
|
Python
Python编程的循环结构小示例(二)
Python编程的循环结构小示例(二)
|
4天前
|
人工智能 数据挖掘 开发者
Python编程:从基础到进阶
【8月更文挑战第59天】本文将带你进入Python的世界,从基础语法到进阶技巧,让你轻松掌握Python编程。我们将通过实例讲解,让你在实际操作中提升技能。无论你是初学者还是有一定基础的开发者,都能在本文中找到适合自己的学习内容。让我们一起探索Python的魅力吧!
|
4天前
|
存储 设计模式 算法
Python编程练习小结
Python编程练习小结
10 1
|
4天前
|
人工智能 小程序 API
ChatTTS+Python编程搞定语音报时小程序
ChatTTS+Python编程搞定语音报时小程序
|
4天前
|
开发者 索引 Python
7个提升python编程的小技巧
7个提升python编程的小技巧
16 0
7个提升python编程的小技巧
|
3天前
|
算法 Python
Python编程的函数—内置函数
Python编程的函数—内置函数