背景
将日志消息广播给所有订阅者(常用于博主,抖音,微博等订阅).
实战
一.生产者
#utf-8
import pika
import sysconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()channel.exchange_declare(exchange='logs',exchange_type='fanout')message = ' '.join(sys.argv[1:]) or "info: Hello World!"
channel.basic_publish(exchange='logs',routing_key='',body=message)
print(" [x] Sent %r" % (message,))
connection.close()
二.消费者
#utf-8
import pikaconnection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()channel.exchange_declare(exchange='logs',exchange_type='fanout')result = channel.queue_declare('',exclusive=True)
queue_name = result.method.queuechannel.queue_bind(exchange='logs',queue=queue_name)print(' [*] Waiting for logs. To exit press CTRL+C')def callback(ch, method, properties, body):print (" [x] %r" % (body,))channel.basic_consume(queue_name,callback, True)channel.start_consuming()