我已经阅读了多篇关于正确设置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')
我观察到,上面的实现是每个作业都在建立一个连接,然后是一个通道。我怀疑这种类型的实现是否会造成不必要的开销。你知道吗
有人能建议正确的方法来处理连接对象吗。我个人觉得为每条消息创建连接肯定是一项开销
https://www.rabbitmq.com/tutorials/amqp-concepts.html#amqp-connections
TL;DR
AMQP连接是长寿命的。AMQP连接的握手过程非常复杂,至少需要7个TCP数据包(如果使用TLS,则需要更多)。最佳实践是重用连接并用通道复用线程之间的连接。你知道吗
连接池详细信息: 至少有10个连接的连接池。如果需要10个以上的连接,可以创建一个新连接。池中最多可以有40个连接。可以设置一个时间限制,在这个时间限制之后连接可以关闭,这样连接就可以关闭,而不是永远在那里。你知道吗
引用:https://www.cloudamqp.com/blog/2018-01-19-part4-rabbitmq-13-common-errors.html
相关问题 更多 >
编程相关推荐