首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >用pika的start_consuming方法中断线程

用pika的start_consuming方法中断线程
EN

Stack Overflow用户
提问于 2015-08-26 15:08:11
回答 1查看 2.7K关注 0票数 8

我有一个使用pika监听rabbitmq新消息的线程。在使用BlockingConnection配置连接之后,我开始通过start_consuming使用消息。我如何中断开始消费方法调用,例如,以优雅的方式停止线程?

EN

回答 1

Stack Overflow用户

发布于 2017-09-30 00:32:13

您可以使用consume generator而不是start_consuming。

代码语言:javascript
复制
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()
票数 8
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/32220057

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档