我有一个 django 应用程序,我想使用来自rabbit mq 的消息。我希望监听器在启动 django 服务器时开始使用。我正在使用 pika 库连接到rabbitmq。提供一些代码示例确实会有帮助。
首先,您需要在 django 项目开始时以某种方式运行您的应用程序https://docs.djangoproject.com/en/2.0/ref/applications/#django.apps.AppConfig.ready 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-6-python.html http://www.rabbitmq.com/tutorials/tutorial-six-python.html
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)