pika消费者随RabbitMQ重启宕机解决。
对于Bunny, Java, .NET, Objective-C, Swift 的rabbitmq客户端拥有自动重连机制, 但是对于python 客户端 目前还没有提供自动重连机制,需要自行实现
一、While
```python
def receive_msg(self):
while True:
try:
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/', credentials=credentials))
channel = connection.channel() # 创建管道
result = channel.queue_declare(queue='URLAdapterQueue', durable=True)
# Don't recover if connection was closed by broker
except pika.exceptions.ConnectionClosedByBroker:
break
# Don't recover on channel errors
except pika.exceptions.AMQPChannelError:
break
# Recover on all other connection errors
except pika.exceptions.AMQPConnectionError:
continue
```
这种方式简单,但不够优雅, 因为异常后,会不停地进行重试。
二、
retry实现
```python
@retry(pika.exceptions.AMQPConnectionError, delay=5, jitter=(1, 3))
def receive_msg(self):
credentials = pika.PlainCredentials('guest', 'guest')
connection = pika.BlockingConnection(
pika.ConnectionParameters(host='localhost', port=5672, virtual_host='/', credentials=credentials))
channel = connection.channel() # 创建管道
result = channel.queue_declare(queue='URLAdapterQueue', durable=True)
try:
channel.start_consuming()
# Don't recover connections closed by server
except pika.exceptions.ConnectionClosedByBroker:
pass```
感谢博主:https://blog.csdn.net/comprel/article/details/93788782?utm_medium=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase&depth_1-utm_source=distribute.pc_relevant.none-task-blog-BlogCommendFromMachineLearnPai2-1.nonecase