如何在带有pika的Rabbitmq中检测已经绑定了队列的交换?

时间:2019-07-03 07:35:14

标签: python rabbitmq

receiver.py:

#!/usr/bin/env python3
import pika
import sys

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

channel.exchange_declare(exchange='device', exchange_type='direct')

result = channel.queue_declare(queue='', exclusive=True)
queue_name = result.method.queue

channel.queue_bind(
    exchange='device', queue=queue_name, routing_key='abc')

print(' [*] Waiting for logs. To exit press CTRL+C')


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

channel.basic_consume(
    queue=queue_name, on_message_callback=callback, auto_ack=True)

channel.start_consuming()

sender.py:

#!/usr/bin/env python3
import pika
import sys

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

channel.exchange_declare(exchange='device', exchange_type='direct')

message = 'Hello World!'
channel.basic_publish(
    exchange='device', routing_key='abc', body=message)
print(" [x] Sent %r:%r" % ('abc', message))
connection.close()

我在receiversender以上都很好,

// first bash session
# python3 receive1.py
 [*] Waiting for logs. To exit press CTRL+C
 [x] 'abc':b'Hello World!'

// second bash session
# python3 send1.py
 [x] Sent 'abc':'Hello World!'

我的问题是:

如果我先致电sender.py,然后致电receiver.py,则receiver.py将不会收到该消息。我知道这是因为sender.py发送消息时,交换实际上没有绑定到任何队列,因此按照rabbitmq的设计,它将丢弃所有没有队列绑定的消息以进行交换。

一种解决方案是使用命名队列,并在sender.py中声明/绑定它。但是,如果我这样做,则如果上次使用方没有从上一个发件人处获取消息,则这次的新使用方可能有机会从上一个发件人处接收旧消息。

对我来说,receiversender之间准备就绪的时间间隔很小。因此,我只是想知道pika是否可能在sender.py中检测到exchange已经与queue绑定了吗?如果不绑定,我会睡一会儿再发送。

有人建议吗?

0 个答案:

没有答案