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)

  

  

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章