在 django 中使用 pika 的 Rabbitmq 监听器 [英] Rabbitmq listener using pika in django
问题描述
我有一个 django 应用程序,我想使用来自 rabbit 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屋!