You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

使用MongoDB作为Celery结果后端时认证失败,但独立连接正常

Celery连接MongoDB结果后端认证失败问题排查与解决

问题核心差异分析

独立脚本与Celery的MongoDB认证逻辑存在关键区别:

  • 你的独立脚本虽然连接字符串指定了celery_db,但实际通过client.admin.command('ismaster')强制使用admin数据库完成认证,而你的admin账号本身拥有admin库的权限,所以连接成功。
  • Celery默认会使用连接字符串中指定的目标数据库(即celery_db)执行认证操作,如果admin账号未被授权在celery_db库上进行认证,就会触发AuthenticationFailed错误。

此外,也可能存在Celery与pymongo版本不兼容,导致连接字符串解析逻辑不一致的情况。

解决方法

方法1:明确指定认证数据库

修改Celery配置中的后端连接字符串,添加authSource=admin参数,强制Celery使用admin库完成认证:

from celery import Celery

app = Celery('tasks',
             broker='amqp://admin:password@rmq.xxxx.net:5672//',
             backend='mongodb://admin:password@mongo.xxxx.net/celery_db?authSource=admin')

app.conf.update(
    task_serializer='json',
    accept_content=['json'], 
    result_serializer='json',
    timezone='Europe/Oslo',
    enable_utc=True,
)

@app.task
def add(x, y):
    return x + y

方法2:为admin账号授予celery_db库的权限

登录MongoDB服务器,执行以下命令为admin账号添加celery_db库的读写权限:

use celery_db
db.grantRolesToUser("admin", [{ role: "readWrite", db: "celery_db" }])

方法3:校验版本兼容性

确保Celery与pymongo版本匹配,部分Celery版本对pymongo有特定版本要求。可以安装兼容的版本组合:

# 示例:安装Celery 5.x搭配pymongo 4.x
pip install celery==5.3.4 pymongo==4.6.0

验证步骤

  1. 重启Celery Worker:
celery -A celery worker -l info
  1. 执行测试任务验证:
from celery import Celery
app = Celery('tasks', backend='mongodb://admin:password@mongo.xxxx.net/celery_db?authSource=admin')
result = app.send_task('celery.add', args=(1,2))
print(result.get())

若任务正常返回结果,则问题已解决。

内容的提问来源于stack exchange,提问作者Mahdi Salehi

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.06.21 11:12:47