zoukankan      html  css  js  c++  java
  • Redis订阅发布模式

    采用订阅发布模式可以将消息分发给所有订阅者,实现消息通知的功能

    redis提供订阅发布模式可供使用,基于redis的链表结构

    代码如下:

    发布者

     1 from redis import StrictRedis
     2 import time
     3 
     4 
     5 redis = StrictRedis(host="192.168.1.1", db=10, password="xxx")
     6 
     7 while True:
     8     msg = str(time.time())+"=msg="
     9     redis.publish("information.important", msg)
    10     print("publish one ===")
    11     time.sleep(1)

    订阅者

     1 from redis import StrictRedis
     2 
     3 
     4 redis = StrictRedis(host="192.168.1.1", db=10, password="xxx")
     5 
     6 sub = redis.pubsub()
     7 sub.subscribe("information.important")
     8 
     9 
    10 for msg in sub.listen():
    11     print(msg)

    订阅到的信息为:

    1 {'type': 'subscribe', 'pattern': None, 'channel': b'information.important', 'data': 1}
    2 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753168.7148438=msg='}
    3 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753169.7158203=msg='}
    4 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753170.7167969=msg='}
    5 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753171.7177732=msg='}
    6 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753172.71875=msg='}
    7 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753173.7197266=msg='}
    8 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753174.720703=msg='}
    9 {'type': 'message', 'pattern': None, 'channel': b'information.important', 'data': b'1623753175.7216797=msg='}

    可以通过订阅相应的通道,来获取相应的消息

  • 相关阅读:
    ASE19 团队项目 模型组 scrum report集合
    ASE19团队项目alpha阶段model组 scrum2 记录
    ASE19团队项目alpha阶段model组 scrum1 记录
    ASE第二次结对编程——Code Search
    jdk中集成的jre和单独安装的jre有什么区别?
    window, linux, mac 比较文件和文件夹的区别
    Java 调用python、ruby 等脚本引擎
    微软软件工程 第一周博客作业
    绩效考核(2018.5.28~2018.6.3)
    数据库需求文档
  • 原文地址:https://www.cnblogs.com/haiton/p/14886671.html
Copyright © 2011-2022 走看看