1. 首先在項目目錄下創(chuàng)建一個異步工作單元文件夾worker
2. 創(chuàng)建init和config文件愧膀,內(nèi)容分別是:
init:
#!/usr/bin/env python
import os
from celery import Celery
from worker import config
# 加載Django的settings
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "social_demo.settings")
# 定義celery
celery_app = Celery('worker')
# config_from_object自動從config模塊里面加載配置
celery_app.config_from_object(config)
# 自動發(fā)現(xiàn)Django中有哪些任務(wù)
celery_app.autodiscover_tasks()
worker:
broker_url = 'redis://127.0.0.1:6379/1'
broker_pool_limit = 100 # Borker 連接池, 默認(rèn)是10
timezone = 'Asia/Shanghai'
# 處理任務(wù)內(nèi)容的類型
accept_content = ['pickle', 'json']
# redis需要字符串類型才能存儲 利用pickle序列化一下
task_serializer = 'pickle'
result_expires = 3600 # 任務(wù)過期時間
# 結(jié)果保存
result_backend = 'redis://127.0.0.1:6379/1'
result_serializer = 'pickle'
result_cache_max = 10000 # 任務(wù)結(jié)果最大緩存數(shù)量
# 日志級別
worker_redirect_stdouts_level = 'INFO'
3. 然后在用接口函數(shù)調(diào)用
# 上傳頭像
def upload_avatar(request):
avatar_file = request.FILES['avatar']
# 通過delay讓celery異步執(zhí)行
logics.upload_avatar.delay(request.user, avatar_file)
return render_json()
4. 服務(wù)器上面開啟服務(wù)化焕,另外再開啟一個celery進程
python manage.py runserver
celery worker -A worker --loglevel=info