首页 > 解决方案 > 如何关闭 Rabbitmq 连接

问题描述

我正在使用 Pika 1.1.0、Python 3.7.4。线程中有消费者。我想杀死线程并关闭rabbitmq连接,但它失败了。我在哪里做错了?我该怎么做?

错误:pika.exceptions.StreamLostError:流连接丢失:IndexError('pop from an empty deque')

def BrokerConnection(username, password):
    try:
        credentials = pika.PlainCredentials(username,password)
        parameters = pika.ConnectionParameters("127.0.0.1","5672","vhost",credentials, heartbeat=0)
        connection = pika.BlockingConnection(parameters)
        channel = connection.channel()
        return connection, channel
    except:
        return None, None

def BrokerListen():
    def BrokerConnect():        
        while True:
            try:
                queue = "test-que"
                connection, channel = BrokerConnection("admin", "123345")

                if channel is not None:
                    brokerConnections.update({"key1":channel})
                    return connection, channel
            except:
                time.sleep(1)
                print("error")

    connection, channel, queue = BrokerConnect()    
    print(f'[*] Waiting for {queue} messages. To exit press CTRL+C')

    def callback(ch, method, properties, body):

        data = json.loads(body)
        print(data)

        ch.basic_ack(delivery_tag=method.delivery_tag)

    channel.basic_consume(queue=queue, on_message_callback=callback)
    channel.start_consuming()

def ConnectionClose():
    channel = brokerConnections["key1"]
    if channel.is_open:
        connection = channel.connection
        channel.stop_consuming()
        connection.close()
        del brokerConnections["key1"]

标签: rabbitmqpika

解决方案


推荐阅读