在Django中使用pika的Rabbitmq侦听器 [英] Rabbitmq listener using pika in django

查看:558
本文介绍了在Django中使用pika的Rabbitmq侦听器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个Django应用程序,我想使用来自兔子mq的消息。我希望侦听器在启动django服务器时开始消耗。我正在使用pika库连接到Rabbitmq。提供一些代码示例确实有帮助。

I have a django application and I want to consume messages from a rabbit mq. I want the listener to start consuming when I start the django server.I am using pika library to connect to rabbitmq.Proving some code example will really help.

推荐答案

首先,您需要以某种方式在django项目
https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.ready

First you need to somehow run your application at the start of the django project 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()

在任何方便的地方都可以

Further in any convenient place

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

这篇关于在Django中使用pika的Rabbitmq侦听器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆