Redis发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息。
Redis 发布订阅(pub/sub)实现了消息系统,发送者(在redis术语中称为发布者)在接收者(订阅者)接收消息时发送消息。传送消息的链路称为信道。
在Redis中,客户端可以订阅任意数量的信道。
发布端代码:
from redis import StrictRedis,ConnectionPool class testGetRedis(): def __init__(self): pool = ConnectionPool(host='localhost', port=6379, db=0) self.redis = StrictRedis(connection_pool=pool) def publishKey(self,channelDescribe): msg = "hello world." self.redis.publish(channelDescribe,msg) if __name__ == '__main__': tr = testGetRedis() channelDescribe = "er_test" tr.publishKey(channelDescribe)
订阅端代码:
from redis import StrictRedis,ConnectionPool class testRedisSub(): def __init__(self): pool = ConnectionPool(host='localhost', port=6379, db=0) self.redis = StrictRedis(connection_pool=pool) def subscribeKey(self,channelDescribe): pub = self.redis.pubsub() pub.psubscribe(channelDescribe) pub.listen() while True: msg = pub.parse_response() print("msg",msg,len(msg)) for i in msg: print("i",i) if __name__ == '__main__': tr = testRedisSub() channelDescribe = "er_test" tr.subscribeKey(channelDescribe)