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

    封装的redis_config

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    import redis
    
    class RedisConfig:
    
        def __init__(self):
            self.__conn = redis.Redis(host='192.168.220.144')
            self.chan_sub = 'redis_queue'
            self.chan_pub = 'redis_queue'
            # 一个给发布端,一个给订阅端
    
        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)  # 选择要监听的queue
            pub.parse_response()  # 准备接收
            return pub
    

    Redis发布端

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    from redis_config import RedisConfig
    
    obj = RedisConfig()
    obj.public('hello world!')
    

    Redis订阅端

    # -*- coding:utf-8 -*-
    __author__ = "MuT6 Sch01aR"
    
    from redis_config import RedisConfig
    
    obj = RedisConfig()
    redis_sub = obj.subscribe()
    
    while True:
        msg = redis_sub.parse_response()
        print(msg)
    

    运行结果

    也可以直接通过redis发布消息

  • 相关阅读:
    NOI2018:屠龙勇士
    Hello world!
    bzoj5月月赛订正
    codeforces906 D
    bzoj2728 [HNOI2012]与非
    bzoj3884上帝与集合的正确用法
    bzoj2817[ZJOI2012]波浪
    2017多校联合赛1[题解]
    论如何优雅的用bitset来求四维偏序
    bzoj1488[HNOI2009]图的同构
  • 原文地址:https://www.cnblogs.com/sch01ar/p/8476805.html
Copyright © 2011-2022 走看看