rabbitmq fanout广播模式

publisher端(.py):

import pika
import sys

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

channel.exchange_declare(exchange = "logs",exchange_type = "fanout")
message = "info:hello world!"
channel.basic_publish(exchange = "logs",
                      routing_key="",
                      body = message)
#不用对队列进行声明,所以routing_key为空
print("[x] sent %r" %message) connection.close()

subscriber端(.py):

import pika

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

channel.exchange_declare(exchange = "logs",
                        exchange_type = "fanout")
#对交换器进行声明fanout模式,名称为“logs”
result = channel.queue_declare(queue = "",exclusive = True)
queue_name = result.method.queue
#随机的队列名
channel.queue_bind(exchange ="logs",queue = queue_name)

print(" [*] Waiting foor logs. To exit press CTRL+C")

def callback(ch,method,properties,body):
    print("[x] %r" %body)

channel.basic_consume(on_message_callback = callback,
                      queue = queue_name,
                      auto_ack = True)
channel.start_consuming()
#消费信息

subscriber端需实时接收publisher端所发送的数据,若先打开publisher端发送信息,然后打开subscriber端会发现先前所发消息丢失,就像女神对你说这周日她有空,你当时耳鸣,而当你恢复听觉想再听她说什么却已经错过那个女神了。

posted on 2020-09-28 11:06  行而下的坏死  阅读(146)  评论(0)    收藏  举报