【问题标题】:Celery configuration in settings.py filesettings.py 文件中的 Celery 配置
【发布时间】:2021-10-04 00:00:03
【问题描述】:

任何人都可以在 Django 的 celery RabbitMQ 中解释这些行。它将在哪个时间使用? 我在没有这些行的情况下在 celery RabbitMq 中运行了 2 个任务(django 中的加法操作和端点)。所以请解释一下什么时候会在settings.py和celery rabbitmq中使用

CELERY_BROKER_URL = 'amqp://localhost'
CELERY_ACCEPT_CONTENT = ['application/json']
CELERY_RESULT_SERIALIZER = 'json'
CELERY_TASK_SERIALIZER = 'json'

__init__.py :
from .celery import app as celery_app

__all__ = ('celery_app',)

提前致谢

【问题讨论】:

    标签: python django rabbitmq celery


    【解决方案1】:

    即使没有这些显式设置,您的任务仍然运行的原因是因为 Celery 在其文档中为它们提供了默认值。

    为了形象化,这是一个我们不会设置 broker_url 的运行。

    $ cat > tasks.py 
    from celery import Celery
    
    app = Celery('my_app')
    $ celery --app=tasks worker --loglevel=INFO
    ...
    - ** ---------- [config]
    - ** ---------- .> app:         my_app:0x7f5a09295160
    - ** ---------- .> transport:   amqp://guest:**@localhost:5672//
    - ** ---------- .> results:     disabled://
    - *** --- * --- .> concurrency: 5 (prefork)
    -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
    --- ***** ----- 
     -------------- [queues]
                    .> celery           exchange=celery(direct) key=celery
    ...
    
    • 如您所见,即使我们没有显式设置代理,它也默认为 transport: amqp://guest:**@localhost:5672//,这是 docs 中所述的 RabbitMQ 的默认值:

    broker_url

    默认值:“amqp://”

    传输部分是要使用的代理实现,而 默认为 amqp,(如果已安装或回退到,则使用 librabbitmq pyamqp)。

    这是一个我们将明确设置broker_url 的运行。要查看差异,假设我们的 RabbitMQ 代理使用不同的密码在 localhost 127.0.0.1 的 666 端口进行侦听。

    $ cat > tasks.py 
    from celery import Celery
    
    app = Celery('my_app')
    
    app.conf.broker_url = "amqp://guest:a-more-secure-password@127.0.0.1:666"
    $ celery --app=tasks worker --loglevel=INFO
    ...
    - ** ---------- [config]
    - ** ---------- .> app:         my_app:0x7fb02579f160
    - ** ---------- .> transport:   amqp://guest:**@127.0.0.1:666//
    - ** ---------- .> results:     disabled://
    - *** --- * --- .> concurrency: 5 (prefork)
    -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker)
    --- ***** ----- 
     -------------- [queues]
                    .> celery           exchange=celery(direct) key=celery
    ...
    
    • 现在,代理设置为我们配置的值transport: amqp://guest:**@127.0.0.1:666//

    如果值与默认值不同,您需要更改这些设置。有关每个可配置设置的详细信息,请参阅docs

    • 覆盖默认值的一个特定用例如上面broker_url 的示例所示,我们需要明确设置它以使用在amqp://guest:a-more-secure-password@127.0.0.1:666 中运行的RabbitMQ,而不是假定的默认值amqp://guest:guest@127.0.0.1:5672 如果我们没有设置它会导致错误 consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 104] Connection reset by peer. Trying again in 2.00 seconds... (1/100)

    其他参考资料:

    【讨论】:

    • 多谢大哥解释清楚。
    猜你喜欢
    • 2012-05-13
    • 1970-01-01
    • 1970-01-01
    • 2021-12-16
    • 2020-11-28
    • 2019-07-16
    • 2018-02-04
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多