所有演示均基于Django2.0
celery是一个基于python开发的简单、灵活且可靠的分布式任务队列框架,支持使用任务队列的方式在分布式的机器/进程/线程上执行任务调度。采用典型的生产者-消费者模型,主要由三部分组成:
消息队列broker:broker实际上就是一个MQ队列服务,可以使用redis、rabbitmq等作为broker 处理任务的消费者workers:broker通知worker队列中有任务,worker去队列中取出任务执行,每一个worker就是一个进程 存储结果的backend:执行结果存储在backend,默认也会存储在broker使用的MQ队列服务中,也可以单独配置用何种服务做backend异步任务
我的异步使用场景为项目上线:前端web上有个上线按钮,点击按钮后发请求给后端,后端执行上线过程要5分钟,后端在接收到请求后把任务放入队列异步执行,同时马上返回给前端一个任务执行中的结果。若果没有异步执行会怎么样呢?同步的情况就是执行过程中前端一直在等后端返回结果,页面转呀转的就转超时了。
异步任务配置
1.安装rabbitmq,这里我们使用rabbitmq作为broker,安装完成后默认启动了,也不需要其他任何配置
# apt-get install rabbitmq-server
2.安装celery
# pip3 install celery
3.celery用在django项目中,django项目目录结构(简化)如下
website/|-- deploy| |-- admin.py| |-- apps.py| |-- __init__.py| |-- models.py| |-- tasks.py| |-- tests.py| |-- urls.py| `-- views.py|-- manage.py|-- README`-- website |-- celery.py |-- __init__.py |-- settings.py |-- urls.py `-- wsgi.py
4.创建 website/celery.py
主文件
from __future__ import absolute_import, unicode_literalsimport osfrom celery import Celery, platforms# set the default Django settings module for the 'celery' program.os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'website.settings')app = Celery('website')# Using a string here means the worker don't have to serialize# the configuration object to child processes.# - namespace='CELERY' means all celery-related configuration keys# should have a `CELERY_` prefix.app.config_from_object('django.conf:settings', namespace='CELERY')# Load task modules from all registered Django app configs.app.autodiscover_tasks()# 允许root 用户运行celeryplatforms.C_FORCE_ROOT = True@app.task(bind=True)def debug_task(self): print('Request: {0!r}'.format(self.request))
5.在 website/__init__.py
文件中增加如下内容,确保django启动的时候这个app能够被加载到
from __future__ import absolute_import# This will make sure the app is always imported when# Django starts so that shared_task will use this app.from .celery import app as celery_app__all__ = ['celery_app']
新闻热点
疑难解答