Python-Redis的发布与订阅
阅读原文时间:2023年10月14日阅读:1

封装的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发布消息