1. 程式人生 > >python操作rabbitmq實現廣播效果

python操作rabbitmq實現廣播效果

連接 lba cti all rec alt aid tin back

生產方(Fanout_Publisher.py)

技術分享圖片
 1 # __author__ = ‘STEVEN‘
 2 import pika
 3 #開啟socket
 4 connection = pika.BlockingConnection(pika.ConnectionParameters(localhost))
 5 #開啟一個通道
 6 channel = connection.channel()
 7 #這裏不用再創建隊列
 8 channel.exchange_declare(exchange=logs,exchange_type=fanout)
 9 #消息內容
10 mes = 
publisher said hello 11 #發布消息exchange=‘logs‘是給他起了一個名字,隨便什麽都行 12 channel.basic_publish(exchange=logs,routing_key=‘‘,body=mes) 13 print([x] send the mes%s to queue%mes) 14 #關閉連接 15 connection.close()
View Code

消費方(Fanout_Consumer.py)

技術分享圖片
 1 # __author__ = ‘STEVEN‘
 2 import pika
 3 #建立socket
 4 connection = pika.BlockingConnection(pika.ConnectionParameters(host=
localhost)) 5 #開啟通道 6 channel = connection.channel() 7 #通道先聲明exchange 8 channel.exchange_declare(exchange=logs,exchange_type=fanout) 9 #聲明queue 10 result = channel.queue_declare(exclusive=True) 11 #獲取queue_name 12 queue_name = result.method.queue 13 #綁定queue 14 channel.queue_bind(exchange=
logs,queue=queue_name) 15 #回調函數 16 def callback(ch,method,properties,body): 17 print([x] receive mess%s%body.decode()) 18 #指定消費相關參數 19 channel.basic_consume(callback,queue=queue_name,no_ack=True) 20 print([*] is waiting for the message) 21 #開啟消費 22 channel.start_consuming()
View Code

與上一篇模式的轉變:

  1.加入了exchange類型,他有如下幾種常用方式:

    技術分享圖片

  2.模式圖:

    技術分享圖片

python操作rabbitmq實現廣播效果