[英]RabbitMQ Python Pika - Connection handling for multiple messages
我一直在閱讀有關正確設置 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; 博士
AMQP 連接是長期存在的。 AMQP 連接的握手過程非常復雜,至少需要 7 個 TCP 數據包(如果使用 TLS,則需要更多)。 最佳實踐是重用連接並在具有通道的線程之間復用連接。
連接池詳細信息:至少有 10 個連接的連接池。 如果需要 10 個以上,則可以創建新連接。 池中的最大連接數可以是 40。 可以設置一個時間限制,在此之后可以關閉連接,以便可以關閉連接而不是永遠存在。
參考: https : //www.cloudamqp.com/blog/2018-01-19-part4-rabbitmq-13-common-errors.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.