【发布时间】:2020-04-20 17:12:42
【问题描述】:
我一直在阅读有关正确设置 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')
我观察到上面的实现是每个作业都建立一个连接,然后是一个通道。我怀疑这种类型的实现是否会造成不必要的开销。
有人可以建议处理连接对象的正确方法吗?我个人觉得为每条消息创建连接肯定是开销
【问题讨论】: