首页 > 解决方案 > 在 django 中使用 pika 的 Rabbitmq 监听器

问题描述

我有一个 django 应用程序,我想使用来自 rabbit mq 的消息。当我启动 django 服务器时,我希望监听器开始消费。我正在使用 pika 库连接到 rabbitmq。证明一些代码示例确实会有所帮助。

标签: djangorabbitmqpika

解决方案


首先,您需要在 django 项目https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.ready开始时以某种方式运行您的应用程序

def ready(self):
    if not settings.IS_ACCEPTANCE_TESTING and not settings.IS_UNITTESTING:
        consumer = AMQPConsuming()
        consumer.daemon = True
        consumer.start()

进一步在任何方便的地方

import threading

import pika
from django.conf import settings


class AMQPConsuming(threading.Thread):
    def callback(self, ch, method, properties, body):
        # do something
        pass

    @staticmethod
    def _get_connection():
        parameters = pika.URLParameters(settings.RABBIT_URL)
        return pika.BlockingConnection(parameters)

    def run(self):
        connection = self._get_connection()
        channel = connection.channel()

        channel.queue_declare(queue='task_queue6')
        print('Hello world! :)')

        channel.basic_qos(prefetch_count=1)
        channel.basic_consume(self.callback, queue='queue')

        channel.start_consuming()

这将有助于 http://www.rabbitmq.com/tutorials/tutorial-six-python.html


推荐阅读