FastAPI中Celery与Redis已运行但任务无法执行问题求助
FastAPI + Celery + Redis 任务无法执行问题排查与解决
问题背景
Redis服务和Celery Worker已正常启动,但任务始终无法执行。已执行的启动命令:
- 启动Redis:
redis-server - 启动Celery Worker:
celery -A core.celery_app_work worker --loglevel=info -P eventlet
已提供Celery Flower输出截图辅助排查。
项目结构
|--backend | |--core | |---celery_app_work.py | |---worker_task.py | | ---main.py
相关代码
celery_app_work.py
from celery import Celery from celery.schedules import crontab celery_app = Celery(__name__, broker='redis://localhost:6379', backend='redis://localhost:6379/0') celery_app.conf.task_routes = {'backend.core.worker_task.*':'example-queue'}
worker_task.py
from .celery_app_work import celery_app data = {'task':'celery'} @celery_app.task(name="create_task") def test_celery(data: str): print('inside celery') for i in range(10): return data
排查与修复方案
1. 队列监听不匹配
你的Celery配置把backend.core.worker_task.*路由到了example-queue队列,但启动Worker时没指定监听这个队列,默认Worker只监听celery队列,导致任务无人处理。
修复命令:启动Worker时指定监听目标队列
celery -A core.celery_app_work worker --loglevel=info -P eventlet -Q example-queue,celery
(保留celery队列是为了兼容默认路由的任务,也可只写example-queue)
2. 任务未被Worker加载
Worker启动时需要能找到任务定义文件,当前配置下可能未自动导入任务模块。
修复方法:在celery_app_work.py末尾添加任务导入
# celery_app_work.py 最后一行 from . import worker_task
3. 任务逻辑异常结束
你的test_celery函数在第一次循环就执行return data,任务会瞬间结束,可能误以为未执行。可以修改函数模拟耗时任务便于验证:
@celery_app.task(name="create_task") def test_celery(data: str): print('inside celery') import time for i in range(10): print(f"Processing step {i}") time.sleep(1) return data
4. FastAPI调用方式验证
确保main.py中正确调用任务:
# main.py 示例代码 from fastapi import FastAPI from core.worker_task import test_celery app = FastAPI() @app.post("/run-task") def run_task(data: str): task = test_celery.delay(data) return {"task_id": task.id, "status": "pending"}
调用该接口后,查看Worker日志是否有inside celery的输出。
5. Redis连接验证
用redis-cli ping测试Redis连接,返回PONG说明连接正常;若有密码,需在Celery的broker/backend URL中添加密码参数:redis://:password@localhost:6379
内容的提问来源于stack exchange,提问作者Pirate_King_Luffy_27
相关产品推荐
相关产品推荐

