参考文档:http://docs.celeryproject.org/en/latest/django/first-steps-with-django.html
1.版本说明
Django: 3.0
Celery: 4.4
RabbitMQ: 3.8.2
Django项目名称: HttpRestServer
Django应用名称: app01
2.celery.py文件
在Django项目的settings.py文件同一级目录下创建文件 celery.py,内容如下:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'HttpRestServer.settings') # 替换 HttpRestServer 为你Django项目的名称
app = Celery('HttpRestServer') # 替换 HttpRestServer 为你Django项目的名称
app.conf.task_default_queue = 'app01' # 默认队列名称为Celery
# Using a string here means the worker doesn'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()
@app.task(bind=True)
def debug_task(self):
print('Request: {0!r}'.format(self.request))
3.配置settings.py
在Django项目的settings.py中添加以下配置
# Celery Config
CELERY_TIMEZONE = 'Asia/Shanghai'
CELERY_BROKER_URL = 'amqp://user:password@rabbitmq-ip:5672' # 将rabbitmq 用户名、密码和IP替换为你的环境
CELERY_RESULT_BACKEND = 'amqp://user:password@rabbitmq-ip:5672' # 将rabbitmq 用户名、密码和IP替换为你的环境
4.配置__init__.py
在Django项目的settings.py文件同一级目录下的__init__.py文件中添加以下内容:
from __future__ import absolute_import, unicode_literals
# 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',)
5.创建tasks.py
在Django项目的应用app01文件夹下创建 tasks.py文件,内容如下:
# Create your tasks here
from __future__ import absolute_import, unicode_literals
from celery import shared_task
@shared_task
def add(x, y):return x + y
@shared_task
def mul(x, y):
return x * y
6.启动Celery
进入Django项目的manage.py这一层级路径,执行以下命令:
$ celery -A HttpRestServer worker -l info
7.调用Celery
进入Django项目的manage.py这一层级路径,执行以下命令:
$ python3 manage.py shell
>>> from app01.tasks import add, mul
>>> res = add.delay(2, 4)
>>> res.id
'893c31ab-e32f-44ee-a321-8b07e9483063'
>>> res.state
'SUCCESS'
>>> res.result
6