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
相关推荐
拾光Ծ16 分钟前
【MySQL】对表数据的操作:增删查改(CRUD)
android·数据库·sql·mysql
这个DBA有点耶13 小时前
2026年分布式数据库有哪些主流选择?先评估这5个维度再决定
数据库·分布式·dba
这个DBA有点耶16 小时前
从MySQL 5.7到8.0:JSON查询性能差在哪?虚拟列索引vs多值索引怎么选
数据库·mysql·架构
胡写代码16 小时前
数据库审计字段,别再每张表各写一套了——我统一成这 6 个字段
数据库
SelectDB20 小时前
为什么 JSON 正在成为分析数据库新的竞争点?
数据库·json·agent
ClouGence21 小时前
开源数据库管理工具 CloudDM 4.2.0 发布,新增 GoldenDB、KingbaseES 等数据源
数据库·dba·devops
发霉的馒头21 小时前
ORA-00845: MEMORY_TARGET not supported on this system的解决方法
数据库
草莓熊Lotso1 天前
【Redis 初阶】Set 类型深度解析:去重集合的运算能力与实战场景
linux·网络·数据库·windows·redis·tcp/ip·缓存
煎饼皮皮侠1 天前
【设计】设计一个web版的数据库管理平台后端(之五) --借鉴mybatis
数据库·mybatis
东风破_1 天前
danci 2:创建的单词书到底存在哪里?从 Supabase 一路理解 ORM、Drizzle 和 RLS
数据库·后端·node.js