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