使用Pika关闭RabbitMQ连接块线程

时间:2017-05-03 20:55:58

标签: python multithreading python-3.x rabbitmq pika

我是从一个单独的线程连接到RabbitMQ但是想让线程从另一个线程停止。

class JobListener(threading.Thread):
    """Listens for jobs"""

    connection = None
    channel = None
    consuming = False

    def run(self):
        try:
            """Start listening for jobs"""
            self.connection = pika.BlockingConnection(
                pika.ConnectionParameters(host=CONN_HOST, credentials=CONN_CREDENTIALS))
            print("[SLAVE/JobListener] AMQP connection established.")
            self.channel = self.connection.channel()
            print("[SLAVE/JobListener] Channel opened.")
            self.channel.queue_declare(queue=QUEUE_NAME)
            print("[SLAVE/JobListener] Queue declared")
            self.channel.basic_consume(self.on_message, queue=QUEUE_NAME, no_ack=True)
            self.consuming = True
            print("[SLAVE/JobListener] Starting consumption...")
            self.channel.start_consuming()
            print("[SLAVE/JobListener] start_consuming() got interrupted externally.")
        finally:
            self.consuming = False

            print("[SLAVE/JobListener] JobListener thread finished.")

    def stop(self):
        """Stop listening for jobs"""
        self.channel.stop_consuming()
        print("[SLAVE/JobListener] Message consumption stopped.")
        self.channel.close()
        print("[SLAVE/JobListener] Channel closed.")
        self.connection.close()
        print("[SLAVE/JobListener] AMQP connection closed.")
        self.consuming = False

    def on_message(self, channel, method, properties, body):
        """Handle incoming message"""
        print("[x] Received %r " % body)

我从另一个主题致电job_listener.start()job_listener.stop()

但是,当我拨打job_listener.stop()时,self.connection.close()的内部呼叫被阻止。为什么呢?

0 个答案:

没有答案