python – 使用pika的start_consuming方法中断线程
发布时间:2020-12-20 13:06:58 所属栏目:Python 来源:网络整理
导读:我有一个线程,它使用pika监听来自rabbitmq的新消息.使用BlockingConnection配置连接后,我开始通过start_consuming消费消息.如何中断启动消耗方法调用,例如,以正常方式停止线程? 解决方法 您可以使用 consume generator而不是start_consuming. import thread
我有一个线程,它使用pika监听来自rabbitmq的新消息.使用BlockingConnection配置连接后,我开始通过start_consuming消费消息.如何中断启动消耗方法调用,例如,以正常方式停止线程?
解决方法
您可以使用
consume generator而不是start_consuming.
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() (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |