【问题标题】:Set Timeout for Pika ioloop async (RabbitMQ)为 Pika ioloop 异步设置超时 (RabbitMQ)
【发布时间】:2011-11-18 09:56:09
【问题描述】:

我需要能够优雅地停止在 Pika ioloop 中工作的消费者(工人)。工人应在 60 秒后停止。当前处理的消息应该完成。

我尝试将connection.close() 放在回调函数中,但这只会停止当前线程,而不是完整的 ioloop。它给出了一个可怕的错误输出。

请参阅我的代码中的第 16 行及以下内容:我使用了(关于 Pika ioloop http://pika.github.com/connecting.html#cps-example 的基本示例:

    from pika.adapters import SelectConnection
    channel = None
    def on_connected(connection):
        connection.channel(on_channel_open)

    def on_channel_open(new_channel):
        global channel
        channel = new_channel
        channel.queue_declare(queue="test", durable=True, exclusive=False, auto_delete=False, callback=on_queue_declared)

    def on_queue_declared(frame):
        channel.basic_consume(handle_delivery, queue='test')

    def handle_delivery(channel, method, header, body):
        print body

        # timer stuff which did NOT work
        global start_time, timeout, connection
        time_diff = time.time()-start_time
        if time_diff > timeout:
            #raise KeyboardInterrupt
            connection.close()

    timeout = 60
    start_time = time.time()

    connection = SelectConnection(parameters, on_connected)

    try:
        connection.ioloop.start()
    except KeyboardInterrupt:
        connection.close()
        connection.ioloop.start()

【问题讨论】:

    标签: python rabbitmq pika


    【解决方案1】:

    您可以在打开的连接上附加超时回调函数。 这是您的示例的额外代码。

    timeout = 60
    
    def on_timeout():
      global connection
      connection.close()
    
    connection.add_timeout(timeout, on_timeout)
    

    【讨论】:

      【解决方案2】:

      你可以尝试使用:

      connection.ioloop.stop()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2012-03-24
        • 1970-01-01
        • 2023-03-09
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2014-05-21
        相关资源
        最近更新 更多