zoukankan      html  css  js  c++  java
  • Python -- Redis 发布订阅

    参考博客:http://www.runoob.com/redis/redis-pub-sub.html

    一、前言

      Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。

      Redis 客户端可以订阅任意数量的频道。

      下图展示了频道 channel1 , 以及订阅这个频道的三个客户端 —— client2 、 client5 和 client1 之间的关系:

      

      当有新消息通过 PUBLISH 命令发送给频道 channel1 时, 这个消息就会被发送给订阅它的三个客户端:

      

    二、事例

     Demo: 

    import redis
    
    
    class RedisHelper:
    
        def __init__(self):
            self.__conn = redis.Redis(host='172.16.200.49')
            self.chan_sub = 'fm104.5'
            self.chan_pub = 'fm104.5'
    
        def public(self, msg):
            self.__conn.publish(self.chan_pub, msg)
            return True
    
        def subscribe(self):
            pub = self.__conn.pubsub()
            pub.subscribe(self.chan_sub)
            pub.parse_response()
            return pub
    
    

      订阅者:

    # -*- coding: UTF-8 -*-
    
    from redis_helper import RedisHelper
    
    obj = RedisHelper()
    redis_sub = obj.subscribe()
    
    while True:
        msg = redis_sub.parse_response()
        print(msg)
    

      发布者:

    # -*- coding: UTF-8 -*-
    
    from redis_helper import RedisHelper
    
    obj = RedisHelper()
    while True:
        msg = input('>>:')
        obj.public(msg)
    

      

  • 相关阅读:
    做过的笔试题
    (转)32位机器中int的字长
    JS_void()
    JS_增加事件,移除事件,动态元素的增删事件研究
    JS_animate 站在别人的肩膀上
    JS_对象的方法
    JS_Class.extend
    JS_返回值
    JS_eventBind
    JS_应用对象的复制
  • 原文地址:https://www.cnblogs.com/bigberg/p/8298411.html
Copyright © 2011-2022 走看看