RabbitMQ_pika重连

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

  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值