django之celery异步任务

1.目录结构

django之celery异步任务_第1张图片

2.在DjangoProject\celery.py下面编写

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery


os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'DjangoProject.settings')  # 设置django环境

app = Celery('DjangoProject')

app.config_from_object('django.conf:settings', namespace='CELERY') #  使用CELERY_ 作为前缀,在settings中写配置

app.autodiscover_tasks()

3.在DjangoProject\__init__.py下面编写

from __future__ import absolute_import, unicode_literals
from .celery import app as celery_app
__all__ = ['celery_app']

4. 在projects\tasks.py下面编写

from __future__ import absolute_import, unicode_literals

import time

from celery import shared_task


@shared_task
def add(x, y):
    time.sleep(30)
    print("celery结果")
    return x + y


@shared_task
def mul(x, y):
    return x * y

5.在DjangoProject\settings.py下面编写

# celery配置

# 消息中间件

CELERY_BROKER_URL = 'redis://47.111.169.26:63790/0' # Broker配置,使用Redis作为消息中间件

CELERY_RESULT_BACKEND = 'redis://47.111.169.26:63790/0' # BACKEND配置,这里使用redis

# 并发任务数worker数量
CELERYD_CONCURRENCY = 2

# 每个worker最大执行任务数
CELERYD_MAX_TASKS_PER_CHILD = 5

CELERY_RESULT_SERIALIZER = 'json' # 结果序列化方案

6.启动celery

celery -A DjangoProject worker -l info -P threads

 

 

你可能感兴趣的:(django,python,django,python,后端)