Celery是異步消息隊列,利用Broker處理耗時操作。(這裡用redis提供隊列服務)
要pip install Celery==4.2
pip install redis
如果 你的項目結構是這樣的:
- proj/
- manage.py
- proj/
- __init__.py
- settings.py
- urls.py
1.配置。
在proj/proj/settings.py下配置broker (celery的配置預設都加CELERY_字首)broker是用來存放消息隊列的
CELERY_BROKER_URL = 'redis://hostname:6379/6' (最後一位‘6’, 是redis的槽位 0-15可用)
(以上是最簡易的配置)
2.添加必要的檔案
(1)添加celery檔案 proj/proj/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', 'proj.settings')
app = Celery('proj')
# 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))
(2)在
proj/proj/__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',)
(3)建立一個app1 這裡的task.py裡面的func()是用來放費時操作的,如:add(),mul()等。
- app1/
- tasks.py
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
@shared_task
def xsum(numbers):
return sum(numbers)
(4)app1裡面的views.py 在恰當的時候調用task.py 裡面的耗時操作。
調用語句如:add.delay(*args, **kwargs)) 函數名.delay(*args, **kwargs)
(而不是函數名().delay()
delay()是異步調用, func()是同步調用)
3.啟動celery
Celery 和Django 是互不相幹的 如果隻跑了Django項目,放在broker裡面的任務并不會執行,兩個都得開。
是以Celery要單獨開啟, 指令如下:celery -A proj worker -l info -c 1
(-l 是指定logging level -c 是指定程序數 不指定就是預設與cpu核心數相同)
指令問題 celery --help or celery worker --help 都可以解決。
這是 最簡單的celery的配置及使用。