Django项目中的Celery异步任务。如何运作?

0 投票
2 回答
2211 浏览
提问于 2025-04-16 19:49

在我的Django项目中,我需要运行一些比较长的任务。于是我决定使用Celery,并把Redis作为消息中介。安装了Redis后,运行时显示:

服务器现在准备好在6379端口接受连接。

接着我安装了django-celery,并进行了配置:

import djcelery
djcelery.setup_loader()
BROKER_HOST = "localhost"
BROKER_PORT = 6379 #redis
BROKER_USER = "guest"
BROKER_PASSWORD = "guest"
BROKER_VHOST = "/"

然后我运行它:

python manage.py celeryd -l DEBUG
[...]
[2011-06-18 10:31:37,913: DEBUG/MainProcess] Starting thread Timer...
[2011-06-18 10:31:37,914: DEBUG/MainProcess] Starting thread Consumer... 
[2011-06-18 10:31:37,914: WARNING/MainProcess] celery@greg... has started.
[2011-06-18 10:31:37,914: DEBUG/MainProcess] Consumer: Re-establishing connection to the broker...

我的示例任务看起来是这样的:

from celery.decorators import task
@task()
def add(x, y):
    return x + y

现在我尝试在命令行中运行它:

In [3]: from message.tasks import add
In [4]: r=add.delay(2, 5)    

但是它等了很久,最后显示了一个错误追踪信息 http://dpaste.com/555939/。这可能是什么原因呢?我是不是漏掉了什么?

2 个回答

0

我不知道这是什么,但我知道RabbitMQ是Celery和Django推荐的消息中间件。我已经在用它了,效果非常好。为什么不试试这个呢?

2

缺少 BROKER_BACKEND 这个设置。下面是一个使用 Redis 的配置示例:

import djcelery
djcelery.setup_loader()

CELERY_RESULT_BACKEND = 'database'

BROKER_BACKEND = 'redis'
BROKER_HOST = 'localhost'
BROKER_PORT = 6379
BROKER_VHOST = '1'

撰写回答