我有一个django应用程序,我想消耗来自兔子mq的消息。我希望听众在启动django服务器时开始消费。我正在使用pika库连接到rabbitmq.Proving一些代码示例将真的有用。
答案 0 :(得分:0)
首先,您需要在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