在celery的配置方法中有个参数叫task_routes,是用来设置不同的任务 消费不同的队列(也就是路由)。
格式如下:
{
‘task name’: {
‘queue’: ‘queue name’ }}
直接上代码,简单明了,目录格式如下:
首先是配置文件 config.init.py
import os
import sys
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(str(BASE_DIR))
class Config(object):
"""配置文件基类"""
""" 项目名称 """
PROJECT_NAME = "crawler_worker"
""" celery backend存放结果 """
CELERY_BACKEND_URL = "redis://127.0.0.1:6379/4"
""" celery broker中间件 """
CELERY_BROKER_URL = "redis://127.0.0.1:6379/5"
""" worker 名称 """
CRAWL_SEND_EMAIL_TASK = "crawl_service.crawl.send_email_task" # 抓取发送邮件任务
CRAWL_SEND_MSG_TASK = "crawl_service.crawl.send_msg_task" # 抓取发送短信任务
settings = Config()
celery应用程序模块配置相关 celery_base.celery_app.py
import os
import sys
import time
import celery
from pathlib import Path
BASE_DIR = Path(__file__).resolve().parent.parent
sys.path.append(str(BASE_DIR))
from config import settings
# 实例化celery对象
celery_app = celery.Celery(
settings.PROJECT_NAME,
backend=settings.CELERY_BACKEND_URL,
broker=settings.CELERY_BROKER_URL,
include=[
"tasks.crawl_send_email",
"tasks.crawl_send_msg"