pyhon rabbitMQ 广播模式

import pika
import sys

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                            exchange_type='fanout')#fanout: 所有bind到此exchange的queue都可以接收消息

#message = ' '.join(sys.argv[1:]) or "info: Hello World!"
message = "info: Hello World!"

channel.basic_publish(exchange='logs',
                      routing_key='',#广播不需要声明queue
                      body=message)
print(" [x] Sent %r" % message)
connection.close()

 

import pika

connection = pika.BlockingConnection(pika.ConnectionParameters(
    host='localhost'))
channel = connection.channel()

channel.exchange_declare(exchange='logs',
                         exchange_type='fanout')

result = channel.queue_declare('',exclusive=True)  #exclusive排他,唯一的, 不指定queue名字,rabbit会随机分配一个名字,exclusive=True会在使用此queue的消费者断开后,自动将queue删除.输入空的queue,传值不能少值
queue_name = result.method.queue#随机queue名字
print('random queuename :',queue_name)

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()
consumer

 

posted @ 2020-10-26 22:02  安好_世界  阅读(95)  评论(0编辑  收藏  举报