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

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

我已经阅读了多个博客和有关正确设置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')

我观察到以上实现是每个工作都在建立连接,然后建立通道。我怀疑这种实现是否会导致不必要的开销。

有人可以建议正确的方法来处理连接对象。我个人觉得为每条消息建立连接肯定是开销]

我已经阅读了多个博客和有关正确设置RabbitMQ连接以进行发布的文档。以下是我的场景:执行一些任务并发布...的几个计划作业...

python rabbitmq pika
1个回答
© www.soinside.com 2019 - 2024. All rights reserved.