【问题标题】:Celery: how to limit number of tasks in queue and stop feeding when full?芹菜:如何限制队列中的任务数量并在满时停止喂食?
【发布时间】:2016-05-15 21:00:27
【问题描述】:

我对 Celery 很陌生,这是我的问题:

假设我有一个脚本,它应该不断地从数据库中获取新数据并使用 Celery 将其发送给工作人员。

tasks.py

# Celery Task
from celery import Celery

app = Celery('tasks', broker='amqp://guest@localhost//')

@app.task
def process_data(x):
    # Do something with x
    pass

fetch_db.py

# Fetch new data from DB and dispatch to workers.
from tasks import process_data

while True:
    # Run DB query here to fetch new data from DB fetched_data

    process_data.delay(fetched_data)

    sleep(30);

我担心的是:每 30 秒获取一次数据。据我所知,process_data() 函数可能需要更长的时间,并且取决于工作人员的数量(特别是如果太少),队列可能会受到限制。

  1. 我无法增加工人数量。
  2. 我可以修改代码以避免在队列已满时向队列提供数据。

问题是如何设置队列大小以及如何知道队列已满?一般情况下,如何处理这种情况?

【问题讨论】:

  • 添加更多工人赶上队列
  • @noorul:这不是我的问题。我无法添加更多工人。如果队列已满,我只能避免喂食。我的问题是如何设置它的大小以及如何知道它已满。
  • 我不确定我们如何定义 Celery 队列的填充度。也许你可以在芹菜队列前面放另一个队列并控制它。
  • 除非您对其进行配置,否则队列不会受到限制。但是它会说您似乎需要重新考虑您的设计。很难说怎么做,因为你给出的代码太通用了。
  • 您能否更改 process_data 使其在某处记录状态,以便您检查其中有多少仍在运行?

标签: python multithreading rabbitmq multiprocessing celery


【解决方案1】:

您可以使用kombu在队列预声明中设置rabbitmq x-max-length

示例:

import time
from celery import Celery
from kombu import Queue, Exchange

class Config(object):
    BROKER_URL = "amqp://guest@localhost//"

    CELERY_QUEUES = (
        Queue(
            'important',
            exchange=Exchange('important'),
            routing_key="important",
            queue_arguments={'x-max-length': 10}
        ),
    )

app = Celery('tasks')
app.config_from_object(Config)


@app.task(queue='important')
def process_data(x):
    pass

或使用Policies

rabbitmqctl set_policy Ten "^one-meg$" '{"max-length-bytes":1000000}' --apply-to queues

【讨论】:

  • 在这种情况下调用 .delay() 会发生什么?
  • 任务将被添加到队列中,但如果队列限制达到Messages will be dropped or dead-lettered from the front of the queue to make room for new messages once the limit is reached.rabbit。通过github 中的问题@ 达到队列长度限制时阻止发布者现在是不可能的
猜你喜欢
  • 1970-01-01
  • 2019-05-29
  • 2020-01-04
  • 2013-12-30
  • 2013-05-05
  • 2011-07-29
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多