让RabbitMQ的连接保持打开状态更好,还是只在必要时打开?

2024-03-29 06:58:20 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个通过一系列测试循环的应用程序。在失败的测试中,它将消息发布到RabbitMQ队列,其他应用程序可以监视并从中获取消息。有数百个测试,可能需要几分钟才能全部完成。由于应用程序定期运行,测试会重复进行

我的问题是,是否最好打开一次连接,并将其保持为打开状态,以便在循环通过所有测试后仅关闭发布?还是只在我需要发布消息并在消息发送后关闭连接时才建立连接更好

另外,如果我的队列已经存在,再次调用queue_declare是否会导致RabbitMQ/pika尝试重新创建队列或覆盖它

这样:

message_con = pika.BlockingConnection(pika.URLParameters(app.conf['pika_url']))
channel = message_con.channel()
channel.queue_declare(queue='outage', durable=True, auto_delete=False, exclusive=False)

for test in tests:    
    # Do tests and stuff....
    if test_failed:
        channel.basic_publish(exchange='', routing_key='outage', body=json.dumps(message), properties=pika.BasicProperties(delivery_mode=2))

message_con.close()

或者这样:

for test in tests:
    # Do tests and stuff....
    if test_failed:
        message_con = pika.BlockingConnection(pika.URLParameters(app.conf['pika_url']))
        channel = message_con.channel()
        channel.queue_declare(queue='outage', durable=True, auto_delete=False, exclusive=False)
        channel.basic_publish(exchange='', routing_key='outage', body=json.dumps(message), properties=pika.BasicProperties(delivery_mode=2))
        message_con.close()

Tags: testfalse应用程序消息message队列queuechannel
1条回答
网友
1楼 · 发布于 2024-03-29 06:58:20

RabbitMQ中的客户端连接意味着长寿命。通道也是长期存在的,但来自客户端的任何错误/异常都可能导致通道关闭。因此,通道的寿命比连接短。强烈建议不要每次操作都打开连接。打开连接需要大量的网络操作和开销。您可以从单个连接打开多个通道

引用-https://www.rabbitmq.com/api-guide.html#connection-and-channel-lifspan

相关问题 更多 >