Djiango配置Celery

1.安装依赖包

复制代码
pip install celery
# 如果使用Redis作为消息代理
pip install redis
# 如果使用RabbitMQ作为消息代理
pip install pika
# 如果需要监控
pip install django-celery-results flower

# Django 5.1.6 + Celery 5.3.x + Redis 4.x
pip install django==5.1.6
pip install celery==5.3.6
pip install redis==4.6.0
pip install django-celery-results==2.5.1
pip install django-celery-beat==2.6.0
pip install eventlet

2.项目结构配置

复制代码
myproject/
├── myproject/
│   ├── __init__.py
│   ├── settings.py
│   ├── urls.py
│   └── wsgi.py
├── app01/
│   ├── views.py
│   ├── urls.py
│   ├── models.py
│   ├── test.py
├── mycelery/
│   ├── __init__.py
│   ├── config.py
│   ├── main.py
│   ├── sms/
│   │   ├── __init__.py
│   │   ├── tasks.py
│   ├── email/
│   │   ├── __init__.py
│   │   ├── tasks.py
├── manage.py
└── requirements.txt

3.配置文件

python 复制代码
# myproject/mycelery/config.py

broker_url = 'redis://localhost:6379/15'
result_backend = 'redis://localhost:6379/14'
python 复制代码
# myproject/mycelery/main.py

import os
# import sys
from celery import Celery

# 设置Django的默认设置模块
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myproject.settings')

app = Celery('myproject')

# 从Django的设置文件中读取Celery配置
# app.config_from_object('django.conf:settings', namespace='CELERY')
app.config_from_object('mycelery.config')

# 自动发现所有Django app中的tasks.py
app.autodiscover_tasks(['mycelery.sms','mycelery.email'])

# 启动celery的命令
# 强烈建议切换目录到celery的根目录下启动
# pip install eventlet
# celery -A mycelery.main worker -l info -P eventlet
python 复制代码
# myproject/mycelery/sms/tasks.py

from celery import shared_task
import logging

logger = logging.getLogger(__name__)
log = logging.getLogger('django')


@shared_task(bind=True, name='sms.import_product_info')
def import_product_info(self, goods_info):
		# 异步逻辑编写
		return "ok"
python 复制代码
# myproject/app01/views.py
from mycelery.sms.tasks import import_product_info

def get(request):
	import_product_info.delay(goods_info)
	return Response("ok")

4.运行redis

复制代码
redis-server.exe redis.windows.conf

5.运行celery

复制代码
celery -A mycelery.main worker -l info -P eventlet
相关推荐
这个DBA有点耶1 天前
MVCC深入:Read View、版本链与快照读——InnoDB并发控制的内核
数据库·mysql·架构
DBA_G1 天前
从地面到云霄:GBase数据库在民航三大场景的落地实践
数据库
自由能燃气设备1 天前
商用全预混低氮冷凝锅炉免费方案vs付费方案对比+选型避坑指南
大数据·数据库·人工智能
科创致远1 天前
科创致远 ESOP 系统核心效能与实战价值展示
大数据·数据库·人工智能·精益工程
2601_962218611 天前
万象生鲜系统称重自动多退少补算法解决生鲜非标品痛点
大数据·数据库·人工智能·python·算法
张洛闻Eren1 天前
k8s云原生【第十课】:水平 Pod 自动扩缩容
运维·数据库·云原生·kubernetes·github
于平安1 天前
MySQL-触发器
数据库·mysql
白远山1 天前
上海24小时自助健身房解决方案实战指南与经验分享
java·数据库·架构·需求分析
Omics Pro1 天前
斯坦福Nature+Science|广义虚拟细胞基础大模型
数据库·人工智能·算法·机器学习·自然语言处理
2603_965148111 天前
AI+API选品:下一代智能商务助手雏形已现
java·大数据·数据库·人工智能·数据挖掘