在 AmazonMQ 维护窗口期间,RabbitMQ自动消费者会出现连接中断的情况,可以通过以下两种方式进行解决:
示例代码:
import pika
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
def callback(ch, method, properties, body):
print("Received %r" % body)
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
try:
channel.start_consuming()
except pika.exceptions.ConnectionClosed:
print('Connection closed! Will try to reconnect in 5 seconds...')
time.sleep(5)
示例代码:
import pika
# connect to RabbitMQ
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
# create consumer
def callback(ch, method, properties, body):
print("Received %r" % body)
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
while True:
try:
channel.start_consuming()
except pika.exceptions.ConnectionClosed:
print('Disconnected! Attempting to reconnect...')
try:
connection = pika.BlockingConnection(pika.ConnectionParameters(host='localhost'))
channel = connection.channel()
channel.basic_consume(queue='hello', on_message_callback=callback, auto_ack=True)
except Exception as e:
print('Could not reconnect:', str(e))