一.配置储值数据,本教程采用redis储值,在setting.py添加配置:
CELERY_BROKER_URL = 'redis://127.0.0.1:6379/2'
CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/2'
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_RESULT_EXPIRES = 30 * 24 * 60 * 60
CELERY_MAX_TASKS_PER_CHILD = 10
二.在wsgi.py同级目录下新建celery.py:
from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'projectNmae.settings')
app = Celery('projectNmae')
app.config_from_object('django.conf:settings', namespace='CELERY')
app.autodiscover_tasks()
三.编辑wsgi.py同级目录下的__init__.py:
from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']
四.在相应的app下面新建tasks.py文件:
from __future__ import absolute_import, unicode_literals
from celery import shared_task
import celery
class BaseTask(celery.Task):
max_retries = 3
def on_failure(self, exc, task_id, args, kwargs, einfo):
print(f"Celery task [{task_id}] failed: [{einfo}], args: [{args}]")
def on_success(self, retval, task_id, args, kwargs):
print(f"Celery task [{task_id}] success: {retval}")
def on_retry(self, exc, task_id, args, kwargs, einfo):
print(f"Celery task [{task_id}] retry: {einfo}")
@celery.task(base=BaseTask)
def add(x, y):
return x + y
五.启动worker:
celery worker -A projectNmae -l debug
celery worker -A projectNmae -l info
win10上运行celery4.x 会报错:
Celery ValueError: not enough values to unpack (expected 3, got 0)
需要先安装eventlet包:pip install eventlet
启动worker的时候在最后加一个参数: -P eventlet
六.触发任务:
from django.http import JsonResponse
from app01 import tasks
def index(request,*args,**kwargs):
res=tasks.add.delay(1,3)
return JsonResponse({'status':res.status,'task_id':res.task_id})
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021070113052132.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjEwNTAzOA==,size_16,color_FFFFFF,t_70#pic_center)
reids可视化中查看执行结果
![在这里插入图片描述](https://img-blog.csdnimg.cn/2021070113073841.png?x-oss-process=image/watermark,type_ZmFuZ3poZW5naGVpdGk,shadow_10,text_aHR0cHM6Ly9ibG9nLmNzZG4ubmV0L3dlaXhpbl80NjEwNTAzOA==,size_16,color_FFFFFF,t_70#pic_center)