是让RabbitMQ的连接保持开放还是只在必要时才开放?

问题描述 投票:0回答:1

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

我的问题是,打开一个连接并保持它的开放性,然后在循环通过所有测试后才关闭,这样会更好吗? 还是只有在我需要发布消息时才建立连接,一旦消息被发送就关闭连接更好?

另外,如果我的队列已经存在,再次调用queue_declare会不会导致RabbitMQpika尝试重新创建队列或覆盖它?

这种方式。

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()
python rabbitmq pika
1个回答
0
投票

RabbitMQ 中的客户端连接旨在实现长寿命。通道也是长寿的,但来自客户端的任何错误异常都可能导致通道的关闭。因此,通道的寿命比连接短。非常不鼓励每次操作打开一个连接。打开一个连接涉及大量的网络操作和开销。你可以从一个连接打开多个通道。

参考资料-------------------------。https:/www.rabbitmq.comapi-guide.html#connection-and-channel-lifspan

© www.soinside.com 2019 - 2024. All rights reserved.