【问题标题】:Creating the first Celery task - Django. Error - "ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//:"创建第一个 Celery 任务 - Django。错误 - “错误/MainProcess] 消费者:无法连接到 amqp://guest:**@127.0.0.1:5672//:”
【发布时间】:2019-11-09 14:00:24
【问题描述】:

我正在尝试创建我的第一个 Celery 任务。该任务将每隔一分钟向同一个人发送相同的电子邮件。

根据文档,我在项目中创建了第一个任务。

from __future__ import absolute_import, unicode_literals
from celery import shared_task
from django.core.mail import send_mail


@shared_task
def send_message():
    to = ['test@test.com', ]
    send_mail('TEST TOPIC',
              'TEST MESSAGE',
              'test@test.com',
              to)

然后,在我项目的 ja 文件夹中,添加 celery.py 文件,如下所示:

from __future__ import absolute_import, unicode_literals
import os
from celery import Celery
from django.conf import settings
from celery.schedules import crontab

# set the default Django settings module for the 'celery' program.
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings')

app = Celery('app_rama')

# Using a string here means the worker doesn't have to serialize
# the configuration object to child processes.
# - namespace='CELERY' means all celery-related configuration keys
#   should have a `CELERY_` prefix.
app.config_from_object('django.conf:settings')

# Load task modules from all registered Django app configs.
app.autodiscover_tasks(settings.INSTALLED_APPS)


app.conf.beat_schedule = {
    'send-message-every-single-minute': {
        'task': 'app.tasks.send_message',
        'schedule': crontab(),  # change to `crontab(minute=0, hour=0)` if you want it to run daily at midnight
    },
}

然后在我的项目的__int__.py文件中添加:

from __future__ import absolute_import, unicode_literals

# This will make sure the app is always imported when
# Django starts so that shared_task will use this app.
from .celery import app as celery_app

__all__ = ('celery_app',)

我尝试做的最后一件事是运行命令:

celery -A app_rama worker -l info

然后我收到以下错误:

[2019-06-27 16:01:26,750: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [WinError 10061]

我尝试了论坛上的许多解决方案,但没有找到正确的解决方案。 在我的 settings.py 文件中添加以下设置也没有帮助我:

CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//'

如何解决此错误,以便我的任务在应用程序的后台运行?

【问题讨论】:

    标签: django celery django-celery


    【解决方案1】:

    您的 Celery 代理可能配置错误。阅读“Using RabbitMQ”文档以了解如何正确设置 RabbitMQ(我假设您想使用 RabbitMQ,因为您在示例中使用了“amqp”协议)。

    我建议使用 Redis 学习 Celery,因为它更易于设置和管理。然后,一旦您了解了基础知识,您可能会决定迁移到 RabbitMQ 或其他一些受支持的代理...

    另外,验证您的 RabbitMQ 服务器是否正常运行。如果您使用 Windows,请确保其上的某些软件不会阻止用户进程连接到 localhost:5672。

    【讨论】:

      猜你喜欢
      • 2023-03-14
      • 2019-01-10
      • 2020-12-30
      • 2020-03-12
      • 2013-08-10
      • 2020-06-07
      • 2018-01-22
      • 2018-10-24
      • 2023-01-10
      相关资源
      最近更新 更多