大家好,今天更新了,大家在编程的时候是不是有时候需要一种很奇怪的功能,好友订阅了你的内容,你在发布新内容的时候需要发邮件通知好友订阅的内容更新了,那么在这个时候我们就用到了redis的发布订阅模式下面就让我带领大家一起看一下发布订阅模式如何使用吧
import redis
class RedisRub:
def __init__(self, host='101.43.29.136', port=6379):
self.redis_conn = redis.Redis(host=host, port=port)
def handle_message(self, message):
print('Received message:', message['data'].decode('utf-8'))
def redis_rub(self):
p = self.redis_conn.pubsub()
p.psubscribe('channel:*')
p.subscribe(**{'channel:1': self.handle_message, 'channel:2': self.handle_message})
for message in p.listen():
pass
if __name__ == '__main__':
rub = RedisRub()
rub.redis_rub()
import redis
class RedisPu:
def __init__(self, host='101.43.29.136', port=6379):
self.r = redis.Redis(host=host, port=port)
def publish_message(self, channel, message):
self.r.publish(channel, message)
def redis_publish(self):
# 发布消息到频道 channel:1
# self.publish_message('channel:1', 'Hello, Redis!')
# 发布消息到频道 channel:2
self.publish_message('channel:2', '你好呀')
if __name__ == '__main__':
redis_pub = RedisPu()
redis_pub.redis_publish()