django - 在 django 中使用 pika 的 Rabbitmq 监听器
问题描述
我有一个 django 应用程序,我想使用来自 rabbit mq 的消息。当我启动 django 服务器时,我希望监听器开始消费。我正在使用 pika 库连接到 rabbitmq。证明一些代码示例确实会有所帮助。
解决方案
首先,您需要在 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
推荐阅读
- javascript - 保留请求上下文是否有时间限制?
- java - AirFlow/DAG 中的任务如何找到可执行文件,这些可执行文件实现了任务应该执行的功能?
- graphviz - Dask 自定义图形可视化
- c++ - 在泛型编程中使用placement new
- javascript - 按下回车键时显示 div
- javascript - 试图从 API 中获取,如何仅获取“1”行
- javascript - 如何调试一个 Firefox 扩展?
- python - 创建 2D numpy 数组的最快方法,该数组从 0 开始,在行中增加 1,然后继续到列?
- amazon-s3 - 使用 Exceljs 将文件写入 s3 存储桶
- java - 更改圆形显示动画的颜色