Python pika的启动消耗法中断线程
我有一个线程,它使用pika侦听来自rabbitmq的新消息。使用BlockingConnection配置连接后,我通过start\u consuming开始使用消息。如何中断start consuming方法调用,例如,以优雅的方式停止线程?您可以使用代替start\u consumingPython pika的启动消耗法中断线程,python,rabbitmq,pika,Python,Rabbitmq,Pika,我有一个线程,它使用pika侦听来自rabbitmq的新消息。使用BlockingConnection配置连接后,我通过start\u consuming开始使用消息。如何中断start consuming方法调用,例如,以优雅的方式停止线程?您可以使用代替start\u consuming import threading import pika class WorkerThread(threading.Thread): def __init__(self): s
import threading
import pika
class WorkerThread(threading.Thread):
def __init__(self):
super(WorkerThread, self).__init__()
self._is_interrupted = False
def stop(self):
self._is_interrupted = True
def run(self):
connection = pika.BlockingConnection(pika.ConnectionParameters())
channel = connection.channel()
channel.queue_declare("queue")
for message in channel.consume("queue", inactivity_timeout=1):
if self._is_interrupted:
break
if not message:
continue
method, properties, body = message
print(body)
def main():
thread = WorkerThread()
thread.start()
# some main thread activity ...
thread.stop()
thread.join()
if __name__ == "__main__":
main()
是否向您的消费者发送基本取消?让您的消费者从控制队列中侦听,该队列在消费者需要停止时注入“退出”消息?
频道。停止消费()
。当您收到“退出”消息时,在注册为basic\u-consume
的回调中调用它。将您优雅的停止指令放在频道之后。start\u consuming()
。非活动\u timeout=1
参数和continue
语句是天才!谢谢你,这是一个繁忙的等待循环,但是pika连接不是线程安全的,这是最好的答案。