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



浙公网安备 33010602011771号