第一步:创建订阅发布类
import redis
class RedisHelper:
def __init__(self):
self.__conn = redis.Redis(host='localhost')
self.chan_sub = 'channl'
def public(self,msg):
self.__conn.publish(self.chan_sub,msg)
return True
def subscribe(self):
pub = self.__conn.pubsub()
pub.subscribe(self.chan_sub)
return pub
第二步:发布消息
obj = RedisHelper()
for i in range(5):
obj.public('hello world','------',i)
第三步:订阅消息
obj = RedisHelper()
redis_sub = obj.subscribe()
while True:
msg = redis_sub.listen()
for i in msg:
if i['type']=='message':
print(str(i['channel'],encoding='utf-8')+ ":" + str(i["data"], encoding="utf-8"))
elif i['type'] =='subscrube':
print(str(i["chennel"], encoding="utf-8"))
print(i)