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 实现消息发布/订阅模型

相关文章
|
1天前
|
机器学习/深度学习 人工智能 数据可视化
Python:探索编程之美
Python:探索编程之美
9 0
|
1天前
|
机器学习/深度学习 人工智能 数据处理
Python编程的魅力与实践
Python编程的魅力与实践
|
2天前
|
SQL 关系型数据库 MySQL
第十三章 Python数据库编程
第十三章 Python数据库编程
|
2天前
|
存储 网络协议 关系型数据库
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
Python从入门到精通:2.3.2数据库操作与网络编程——学习socket编程,实现简单的TCP/UDP通信
|
8天前
|
安全 数据处理 开发者
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
《Python 简易速速上手小册》第7章:高级 Python 编程(2024 最新版)
19 1
|
8天前
|
人工智能 数据挖掘 程序员
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
《Python 简易速速上手小册》第1章:Python 编程入门(2024 最新版)
35 0
|
9天前
|
API Python
Python模块化编程:面试题深度解析
【4月更文挑战第14天】了解Python模块化编程对于构建大型项目至关重要,它涉及代码组织、复用和维护。本文深入探讨了模块、包、导入机制、命名空间和作用域等基础概念,并列举了面试中常见的模块导入混乱、不适当星号导入等问题,强调了避免循环依赖、合理使用`__init__.py`以及理解模块作用域的重要性。掌握这些知识将有助于在面试中自信应对模块化编程的相关挑战。
21 0
|
9天前
|
Python
Python金融应用编程:衍生品定价和套期保值的随机过程
Python金融应用编程:衍生品定价和套期保值的随机过程
24 0
|
10天前
|
Python
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
python面型对象编程进阶(继承、多态、私有化、异常捕获、类属性和类方法)(上)
52 0
|
10天前
|
机器学习/深度学习 算法 定位技术
python中使用马尔可夫决策过程(MDP)动态编程来解决最短路径强化学习问题
python中使用马尔可夫决策过程(MDP)动态编程来解决最短路径强化学习问题
24 1