python - RabbitMQ Python Pika - 多个消息的连接处理

标签 python rabbitmq pika

我一直在阅读多个关于正确设置 RabbitMQ 连接以进行发布的博客和文档。以下是我的场景

  • 很少有计划作业执行某些任务并将输出发布到 RabbitMQ
  • 作业以不同的时间间隔运行,但输出将发布到同一个 RabbitMQ 队列

下面是实现

def get_credentials(self):
    print ("Host ", config_reader.get_lookup_data('RABBITMQ', 'host'))
    credentials = pika.PlainCredentials(config_reader.get_lookup_data('RABBITMQ', 'user'),
                                        config_reader.get_lookup_data('RABBITMQ', 'password'))
    return credentials

def publish_message(self, message):
    print ("Publish message" , message)
    connection = pika.BlockingConnection(
        pika.ConnectionParameters(host=config_reader.get_lookup_data('RABBITMQ', 'host'),
                                  credentials=self.get_credentials()))
    channel = connection.channel()
    channel.exchange_declare(exchange=config_reader.get_lookup_data('RABBITMQ', 'exchange'), passive=True)
    result = channel.queue_declare(exclusive=False,
                                   queue=config_reader.get_lookup_data('RABBITMQ', 'sensor_queue'))
    channel.queue_bind(result.method.queue,
                       exchange=config_reader.get_lookup_data('RABBITMQ', 'exchange'),
                       routing_key=config_reader.get_lookup_data('RABBITMQ', 'routing_key'))
    print ('Publishing message ', message)
    channel.basic_publish(exchange=config_reader.get_lookup_data('RABBITMQ', 'exchange'), body=json.dumps(message),
                          routing_key=config_reader.get_lookup_data('RABBITMQ', 'routing_key'),
                          properties=pika.BasicProperties(
                              headers={'Content-Type': 'application/json'}  # Add a key/value header
                          ))
    print ('published')

我观察到上面的实现是每个作业都建立一个连接,然后建立一个 channel 。我怀疑这种类型的实现是否会造成不必要的开销。

有人可以建议处理连接对象的正确方法吗?我个人认为为每条消息创建连接肯定是开销

最佳答案

https://www.rabbitmq.com/tutorials/amqp-concepts.html#amqp-connections

TL;DR

AMQP 连接是长期存在的。 AMQP 连接的握手过程相当复杂,至少需要 7 个 TCP 数据包(如果使用 TLS,则需要更多)。最佳实践是重用连接并将线程与 channel 之间的连接复用。

连接池详细信息: 连接池至少有 10 个连接。如果需要超过 10 个,则可以创建新连接。池中的最大连接数为 40。可以设置关闭连接的时间限制,这样连接就可以关闭而不是永远存在。

引用:https://www.cloudamqp.com/blog/2018-01-19-part4-rabbitmq-13-common-errors.html

关于python - RabbitMQ Python Pika - 多个消息的连接处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59556540/

相关文章:

python - 矢量化 numpy.einsum

python - PyTorch 回归产生与预测相同的数字

go - 如何使 rabbitmq 消费者超时?

Rabbitmq 集群在 ec2 上不起作用

python - 使用 Python、Pika 和 AMQP 设计异步 RPC 应用程序的最佳模式是什么?

python - 为什么重启消费者后RabbitMQ队列中的消息丢失了?

python - 如何在 Airflow 中运行 bash 脚本文件

python - 合并相同标签进行计数

python-3.x - RabbitMQ Pika 连接重置 , (-1, ConnectionResetError(104, 'Connection reset by peer' ))

python - 允许 RabbitMQ 和 Pika 保持连接始终打开