RabbitMQ - 3 fanout模式
Putting it all together
send.py
#!/usr/bin/env python
import pika
import sys
connection = 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()
receive.py
#!/usr/bin/env python
import pika
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.exchange_declare(exchange='logs', exchange_type='fanout')
result = channel.queue_declare(queue='', exclusive=True) # 临时队列
queue_name = result.method.queue
channel.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=queue_name, on_message_callback=callback, auto_ack=True)
channel.start_consuming()
队列绑定图:
可能有的同学会问:为什么没有指定routing_key呢? -- 由于fanout这种模式的特点,它类似于广播的模式,即使写了也会被忽略掉。
临时队列
使用场景:1. 在连接到RabbitMQ时需要一个全新的空的队列 2. 在consumer连接关闭时队列也被删除时
1. result = channel.queue_declare(queue='') 2. result = channel.queue_declare(queue='', exclusive=True)


浙公网安备 33010602011771号