arn*_*nau 7 python rabbitmq pika
我有一个线程,它使用pika监听来自Rabbitmq的新消息。使用BlockingConnection配置连接后,我开始通过start_consumption来消耗消息。如何中断开始消耗方法的调用,例如以优雅的方式停止线程?
小智 7
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()
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1397 次 |
| 最近记录: |