为什么芹菜路径既有“队列”又有“路由密钥”?

2024-04-28 22:21:14 发布

您现在位置:Python中文网/ 问答频道 /正文

我对AMQP的理解是,消息只有以下组件:

  1. 消息正文
  2. 路由密钥
  3. 交易所

队列附加到交换机。消息不能有任何队列知识。它们只是发送到一个exchange,然后根据exchange类型和路由密钥,将消息路由到一个或多个队列。

在芹菜中,建议通过CELERY_ROUTES设置路由任务。从文档中,CELERY_ROUTES是。。。

A list of routers, or a single router used to route tasks to queues. http://celery.readthedocs.org/en/latest/configuration.html#message-routing

包括一个例子。。。

To route a task to the feed_tasks queue, you can add an entry in the CELERY_ROUTES setting:

CELERY_ROUTES = {
    'feeds.tasks.import_feed': {
        'queue': 'feed_tasks',
        'routing_key': 'feed.import',
    },
}

但请稍等——根据AMQP的说法,消息只有一个路由密钥!“排队”在那里干什么?

此外,还有一个默认队列的概念。如果调用的任务不是由CELERY_ROUTES捕获的,则返回到CELERY_DEFAULT_QUEUE。但是,在AMQP中,消息不知道队列。那不应该是默认的路由密钥吗?


Tags: thetoimport消息路由amqpexchange队列
2条回答

在那里声明队列的目的是让芹菜创建这些队列并使用RabbitMQ设置配置。

对于较低级别的AMQP客户机,您需要先声明队列,然后声明交换,最后将交换绑定到队列。稍后在发布邮件时,您只需将邮件发送到exchange。

看起来芹菜是用这种结构自动完成的。

确实,在芹菜上,当您进入队列时会有一点混乱,您必须记住的一点是,queue参数指的是芹菜Kombu队列对象,而不是直接指向AMQP队列,您可以通过阅读本文extract from the docs来理解这一点。 当然,芹菜创建队列并用同一个名称交换的事实是队列参数使用混乱的根源。 在文档中,您可以阅读以下段落:

If you have another queue but on another exchange you want to add, just specify a custom exchange and exchange type:

CELERY_QUEUES = (
    Queue('feed_tasks',    routing_key='feed.#'),
    Queue('regular_tasks', routing_key='task.#'),
    Queue('image_tasks',   exchange=Exchange('mediatasks', type='direct'),
                       routing_key='image.compress'),
)

这样就可以在同一个交换上绑定两个不同的队列。 在仅使用exchange和密钥路由任务之后,可以使用Routers类

class MyRouter(object):

    def route_for_task(self, task, args=None, kwargs=None):
        if task == 'myapp.tasks.compress_video':
            return {'exchange': 'video',
                    'exchange_type': 'topic',
                    'routing_key': 'video.compress'}
        return None

更多http://celery.readthedocs.org/en/latest/userguide/routing.html#routers

相关问题 更多 >