| 1 |
.. _guide-routing: |
| 2 |
|
| 3 |
=============== |
| 4 |
Routing Tasks |
| 5 |
=============== |
| 6 |
|
| 7 |
.. note:: |
| 8 |
|
| 9 |
Alternate routing concepts like topic and fanout is not |
| 10 |
available for all transports, please consult the |
| 11 |
:ref:`transport comparison table <kombu:transport-comparison>`. |
| 12 |
|
| 13 |
.. contents:: |
| 14 |
:local: |
| 15 |
|
| 16 |
|
| 17 |
.. _routing-basics: |
| 18 |
|
| 19 |
Basics |
| 20 |
====== |
| 21 |
|
| 22 |
.. _routing-automatic: |
| 23 |
|
| 24 |
Automatic routing |
| 25 |
----------------- |
| 26 |
|
| 27 |
The simplest way to do routing is to use the |
| 28 |
:setting:`task_create_missing_queues` setting (on by default). |
| 29 |
|
| 30 |
With this setting on, a named queue that's not already defined in |
| 31 |
:setting:`task_queues` will be created automatically. This makes it easy to |
| 32 |
perform simple routing tasks. |
| 33 |
|
| 34 |
Say you have two servers, `x`, and `y` that handle regular tasks, |
| 35 |
and one server `z`, that only handles feed related tasks. You can use this |
| 36 |
configuration:: |
| 37 |
|
| 38 |
task_routes = {'feed.tasks.import_feed': {'queue': 'feeds'}} |
| 39 |
|
| 40 |
With this route enabled import feed tasks will be routed to the |
| 41 |
`"feeds"` queue, while all other tasks will be routed to the default queue |
| 42 |
(named `"celery"` for historical reasons). |
| 43 |
|
| 44 |
Alternatively, you can use glob pattern matching, or even regular expressions, |
| 45 |
to match all tasks in the ``feed.tasks`` name-space: |
| 46 |
|
| 47 |
.. code-block:: python |
| 48 |
|
| 49 |
app.conf.task_routes = {'feed.tasks.*': {'queue': 'feeds'}} |
| 50 |
|
| 51 |
If the order of matching patterns is important you should |
| 52 |
specify the router in *items* format instead: |
| 53 |
|
| 54 |
.. code-block:: python |
| 55 |
|
| 56 |
task_routes = ([ |
| 57 |
('feed.tasks.*', {'queue': 'feeds'}), |
| 58 |
('web.tasks.*', {'queue': 'web'}), |
| 59 |
(re.compile(r'(video|image)\.tasks\..*'), {'queue': 'media'}), |
| 60 |
],) |
| 61 |
|
| 62 |
.. note:: |
| 63 |
|
| 64 |
The :setting:`task_routes` setting can either be a dictionary, or a |
| 65 |
list of router objects, so in this case we need to specify the setting |
| 66 |
as a tuple containing a list. |
| 67 |
|
| 68 |
After installing the router, you can start server `z` to only process the feeds |
| 69 |
queue like this: |
| 70 |
|
| 71 |
.. code-block:: console |
| 72 |
|
| 73 |
user@z:/$ celery -A proj worker -Q feeds |
| 74 |
|
| 75 |
You can specify as many queues as you want, so you can make this server |
| 76 |
process the default queue as well: |
| 77 |
|
| 78 |
.. code-block:: console |
| 79 |
|
| 80 |
user@z:/$ celery -A proj worker -Q feeds,celery |
| 81 |
|
| 82 |
.. _routing-changing-default-queue: |
| 83 |
|
| 84 |
Changing the name of the default queue |
| 85 |
~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 86 |
|
| 87 |
You can change the name of the default queue by using the following |
| 88 |
configuration: |
| 89 |
|
| 90 |
.. code-block:: python |
| 91 |
|
| 92 |
app.conf.task_default_queue = 'default' |
| 93 |
|
| 94 |
.. _routing-autoqueue-details: |
| 95 |
|
| 96 |
How the queues are defined |
| 97 |
~~~~~~~~~~~~~~~~~~~~~~~~~~ |
| 98 |
|
| 99 |
The point with this feature is to hide the complex AMQP protocol for users |
| 100 |
with only basic needs. However -- you may still be interested in how these queues |
| 101 |
are declared. |
| 102 |
|
| 103 |
A queue named `"video"` will be created with the following settings: |
| 104 |
|
| 105 |
.. code-block:: javascript |
| 106 |
|
| 107 |
{'exchange': 'video', |
| 108 |
'exchange_type': 'direct', |
| 109 |
'routing_key': 'video'} |
| 110 |
|
| 111 |
The non-AMQP backends like `Redis` or `SQS` don't support exchanges, |
| 112 |
so they require the exchange to have the same name as the queue. Using this |
| 113 |
design ensures it will work for them as well. |
| 114 |
|
| 115 |
.. _routing-manual: |
| 116 |
|
| 117 |
Manual routing |
| 118 |
-------------- |
| 119 |
|
| 120 |
Say you have two servers, `x`, and `y` that handle regular tasks, |
| 121 |
and one server `z`, that only handles feed related tasks, you can use this |
| 122 |
configuration: |
| 123 |
|
| 124 |
.. code-block:: python |
| 125 |
|
| 126 |
from kombu import Queue |
| 127 |
|
| 128 |
app.conf.task_default_queue = 'default' |
| 129 |
app.conf.task_queues = ( |
| 130 |
Queue('default', routing_key='task.#'), |
| 131 |
Queue('feed_tasks', routing_key='feed.#'), |
| 132 |
) |
| 133 |
app.conf.task_default_exchange = 'tasks' |
| 134 |
app.conf.task_default_exchange_type = 'topic' |
| 135 |
app.conf.task_default_routing_key = 'task.default' |
| 136 |
|
| 137 |
:setting:`task_queues` is a list of :class:`~kombu.entity.Queue` |
| 138 |
instances. |
| 139 |
If you don't set the exchange or exchange type values for a key, these |
| 140 |
will be taken from the :setting:`task_default_exchange` and |
| 141 |
:setting:`task_default_exchange_type` settings. |
| 142 |
|
| 143 |
To route a task to the `feed_tasks` queue, you can add an entry in the |
| 144 |
:setting:`task_routes` setting: |
| 145 |
|
| 146 |
.. code-block:: python |
| 147 |
|
| 148 |
task_routes = { |
| 149 |
'feeds.tasks.import_feed': { |
| 150 |
'queue': 'feed_tasks', |
| 151 |
'routing_key': 'feed.import', |
| 152 |
}, |
| 153 |
} |
| 154 |
|
| 155 |
|
| 156 |
You can also override this using the `routing_key` argument to |
| 157 |
:meth:`Task.apply_async`, or :func:`~celery.execute.send_task`: |
| 158 |
|
| 159 |
>>> from feeds.tasks import import_feed |
| 160 |
>>> import_feed.apply_async(args=['http://cnn.com/rss'], |
| 161 |
... queue='feed_tasks', |
| 162 |
... routing_key='feed.import') |
| 163 |
|
| 164 |
|
| 165 |
To make server `z` consume from the feed queue exclusively you can |
| 166 |
start it with the :option:`celery worker -Q` option: |
| 167 |
|
| 168 |
.. code-block:: console |
| 169 |
|
| 170 |
user@z:/$ celery -A proj worker -Q feed_tasks --hostname=z@%h |
| 171 |
|
| 172 |
Servers `x` and `y` must be configured to consume from the default queue: |
| 173 |
|
| 174 |
.. code-block:: console |
| 175 |
|
| 176 |
user@x:/$ celery -A proj worker -Q default --hostname=x@%h |
| 177 |
user@y:/$ celery -A proj worker -Q default --hostname=y@%h |
| 178 |
|
| 179 |
If you want, you can even have your feed processing worker handle regular |
| 180 |
tasks as well, maybe in times when there's a lot of work to do: |
| 181 |
|
| 182 |
.. code-block:: console |
| 183 |
|
| 184 |
user@z:/$ celery -A proj worker -Q feed_tasks,default --hostname=z@%h |
| 185 |
|
| 186 |
If you have another queue but on another exchange you want to add, |
| 187 |
just specify a custom exchange and exchange type: |
| 188 |
|
| 189 |
.. code-block:: python |
| 190 |
|
| 191 |
from kombu import Exchange, Queue |
| 192 |
|
| 193 |
app.conf.task_queues = ( |
| 194 |
Queue('feed_tasks', routing_key='feed.#'), |
| 195 |
Queue('regular_tasks', routing_key='task.#'), |
| 196 |
Queue('image_tasks', exchange=Exchange('mediatasks', type='direct'), |
| 197 |
routing_key='image.compress'), |
| 198 |
) |
| 199 |
|
| 200 |
If you're confused about these terms, you should read up on AMQP. |
| 201 |
|
| 202 |
.. seealso:: |
| 203 |
|
| 204 |
In addition to the :ref:`amqp-primer` below, there's |
| 205 |
`Rabbits and Warrens`_, an excellent blog post describing queues and |
| 206 |
exchanges. There's also The `CloudAMQP tutorial`, |
| 207 |
For users of RabbitMQ the `RabbitMQ FAQ`_ |
| 208 |
could be useful as a source of information. |
| 209 |
|
| 210 |
.. _`Rabbits and Warrens`: http://web.archive.org/web/20160323134044/http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/ |
| 211 |
.. _`CloudAMQP tutorial`: amqp in 10 minutes part 3 |
| 212 |
https://www.cloudamqp.com/blog/2015-09-03-part4-rabbitmq-for-beginners-exchanges-routing-keys-bindings.html |
| 213 |
.. _`RabbitMQ FAQ`: https://www.rabbitmq.com/faq.html |
| 214 |
|
| 215 |
.. _routing-special_options: |
| 216 |
|
| 217 |
Special Routing Options |
| 218 |
======================= |
| 219 |
|
| 220 |
.. _routing-options-rabbitmq-priorities: |
| 221 |
|
| 222 |
RabbitMQ Message Priorities |
| 223 |
--------------------------- |
| 224 |
:supported transports: RabbitMQ |
| 225 |
|
| 226 |
.. versionadded:: 4.0 |
| 227 |
|
| 228 |
Queues can be configured to support priorities by setting the |
| 229 |
``x-max-priority`` argument: |
| 230 |
|
| 231 |
.. code-block:: python |
| 232 |
|
| 233 |
from kombu import Exchange, Queue |
| 234 |
|
| 235 |
app.conf.task_queues = [ |
| 236 |
Queue('tasks', Exchange('tasks'), routing_key='tasks', |
| 237 |
queue_arguments={'x-max-priority': 10}), |
| 238 |
] |
| 239 |
|
| 240 |
A default value for all queues can be set using the |
| 241 |
:setting:`task_queue_max_priority` setting: |
| 242 |
|
| 243 |
.. code-block:: python |
| 244 |
|
| 245 |
app.conf.task_queue_max_priority = 10 |
| 246 |
|
| 247 |
A default priority for all tasks can also be specified using the |
| 248 |
:setting:`task_default_priority` setting: |
| 249 |
|
| 250 |
.. code-block:: python |
| 251 |
|
| 252 |
app.conf.task_default_priority = 5 |
| 253 |
|
| 254 |
.. _amqp-primer: |
| 255 |
|
| 256 |
|
| 257 |
Redis Message Priorities |
| 258 |
------------------------ |
| 259 |
:supported transports: Redis |
| 260 |
|
| 261 |
While the Celery Redis transport does honor the priority field, Redis itself has |
| 262 |
no notion of priorities. Please read this note before attempting to implement |
| 263 |
priorities with Redis as you may experience some unexpected behavior. |
| 264 |
|
| 265 |
To start scheduling tasks based on priorities you need to configure queue_order_strategy transport option. |
| 266 |
|
| 267 |
.. code-block:: python |
| 268 |
|
| 269 |
app.conf.broker_transport_options = { |
| 270 |
'queue_order_strategy': 'priority', |
| 271 |
} |
| 272 |
|
| 273 |
|
| 274 |
The priority support is implemented by creating n lists for each queue. |
| 275 |
This means that even though there are 10 (0-9) priority levels, these are |
| 276 |
consolidated into 4 levels by default to save resources. This means that a |
| 277 |
queue named celery will really be split into 4 queues. |
| 278 |
|
| 279 |
The highest priority queue will be named celery, and the other queues will |
| 280 |
have a separator (by default `\x06\x16`) and their priority number appended to |
| 281 |
the queue name. |
| 282 |
|
| 283 |
.. code-block:: python |
| 284 |
|
| 285 |
['celery', 'celery\x06\x163', 'celery\x06\x166', 'celery\x06\x169'] |
| 286 |
|
| 287 |
|
| 288 |
If you want more priority levels or a different separator you can set the |
| 289 |
priority_steps and sep transport options: |
| 290 |
|
| 291 |
.. code-block:: python |
| 292 |
|
| 293 |
app.conf.broker_transport_options = { |
| 294 |
'priority_steps': list(range(10)), |
| 295 |
'sep': ':', |
| 296 |
'queue_order_strategy': 'priority', |
| 297 |
} |
| 298 |
|
| 299 |
The config above will give you these queue names: |
| 300 |
|
| 301 |
.. code-block:: python |
| 302 |
|
| 303 |
['celery', 'celery:1', 'celery:2', 'celery:3', 'celery:4', 'celery:5', 'celery:6', 'celery:7', 'celery:8', 'celery:9'] |
| 304 |
|
| 305 |
|
| 306 |
That said, note that this will never be as good as priorities implemented at the |
| 307 |
broker server level, and may be approximate at best. But it may still be good |
| 308 |
enough for your application. |
| 309 |
|
| 310 |
|
| 311 |
AMQP Primer |
| 312 |
=========== |
| 313 |
|
| 314 |
Messages |
| 315 |
-------- |
| 316 |
|
| 317 |
A message consists of headers and a body. Celery uses headers to store |
| 318 |
the content type of the message and its content encoding. The |
| 319 |
content type is usually the serialization format used to serialize the |
| 320 |
message. The body contains the name of the task to execute, the |
| 321 |
task id (UUID), the arguments to apply it with and some additional |
| 322 |
meta-data -- like the number of retries or an ETA. |
| 323 |
|
| 324 |
This is an example task message represented as a Python dictionary: |
| 325 |
|
| 326 |
.. code-block:: javascript |
| 327 |
|
| 328 |
{'task': 'myapp.tasks.add', |
| 329 |
'id': '54086c5e-6193-4575-8308-dbab76798756', |
| 330 |
'args': [4, 4], |
| 331 |
'kwargs': {}} |
| 332 |
|
| 333 |
.. _amqp-producers-consumers-brokers: |
| 334 |
|
| 335 |
Producers, consumers, and brokers |
| 336 |
--------------------------------- |
| 337 |
|
| 338 |
The client sending messages is typically called a *publisher*, or |
| 339 |
a *producer*, while the entity receiving messages is called |
| 340 |
a *consumer*. |
| 341 |
|
| 342 |
The *broker* is the message server, routing messages from producers |
| 343 |
to consumers. |
| 344 |
|
| 345 |
You're likely to see these terms used a lot in AMQP related material. |
| 346 |
|
| 347 |
.. _amqp-exchanges-queues-keys: |
| 348 |
|
| 349 |
Exchanges, queues, and routing keys |
| 350 |
----------------------------------- |
| 351 |
|
| 352 |
1. Messages are sent to exchanges. |
| 353 |
2. An exchange routes messages to one or more queues. Several exchange types |
| 354 |
exists, providing different ways to do routing, or implementing |
| 355 |
different messaging scenarios. |
| 356 |
3. The message waits in the queue until someone consumes it. |
| 357 |
4. The message is deleted from the queue when it has been acknowledged. |
| 358 |
|
| 359 |
The steps required to send and receive messages are: |
| 360 |
|
| 361 |
1. Create an exchange |
| 362 |
2. Create a queue |
| 363 |
3. Bind the queue to the exchange. |
| 364 |
|
| 365 |
Celery automatically creates the entities necessary for the queues in |
| 366 |
:setting:`task_queues` to work (except if the queue's `auto_declare` |
| 367 |
setting is set to :const:`False`). |
| 368 |
|
| 369 |
Here's an example queue configuration with three queues; |
| 370 |
One for video, one for images, and one default queue for everything else: |
| 371 |
|
| 372 |
.. code-block:: python |
| 373 |
|
| 374 |
from kombu import Exchange, Queue |
| 375 |
|
| 376 |
app.conf.task_queues = ( |
| 377 |
Queue('default', Exchange('default'), routing_key='default'), |
| 378 |
Queue('videos', Exchange('media'), routing_key='media.video'), |
| 379 |
Queue('images', Exchange('media'), routing_key='media.image'), |
| 380 |
) |
| 381 |
app.conf.task_default_queue = 'default' |
| 382 |
app.conf.task_default_exchange_type = 'direct' |
| 383 |
app.conf.task_default_routing_key = 'default' |
| 384 |
|
| 385 |
.. _amqp-exchange-types: |
| 386 |
|
| 387 |
Exchange types |
| 388 |
-------------- |
| 389 |
|
| 390 |
The exchange type defines how the messages are routed through the exchange. |
| 391 |
The exchange types defined in the standard are `direct`, `topic`, |
| 392 |
`fanout` and `headers`. Also non-standard exchange types are available |
| 393 |
as plug-ins to RabbitMQ, like the `last-value-cache plug-in`_ by Michael |
| 394 |
Bridgen. |
| 395 |
|
| 396 |
.. _`last-value-cache plug-in`: |
| 397 |
https://github.com/squaremo/rabbitmq-lvc-plugin |
| 398 |
|
| 399 |
.. _amqp-exchange-type-direct: |
| 400 |
|
| 401 |
Direct exchanges |
| 402 |
~~~~~~~~~~~~~~~~ |
| 403 |
|
| 404 |
Direct exchanges match by exact routing keys, so a queue bound by |
| 405 |
the routing key `video` only receives messages with that routing key. |
| 406 |
|
| 407 |
.. _amqp-exchange-type-topic: |
| 408 |
|
| 409 |
Topic exchanges |
| 410 |
~~~~~~~~~~~~~~~ |
| 411 |
|
| 412 |
Topic exchanges matches routing keys using dot-separated words, and the |
| 413 |
wild-card characters: ``*`` (matches a single word), and ``#`` (matches |
| 414 |
zero or more words). |
| 415 |
|
| 416 |
With routing keys like ``usa.news``, ``usa.weather``, ``norway.news``, and |
| 417 |
``norway.weather``, bindings could be ``*.news`` (all news), ``usa.#`` (all |
| 418 |
items in the USA), or ``usa.weather`` (all USA weather items). |
| 419 |
|
| 420 |
.. _amqp-api: |
| 421 |
|
| 422 |
Related API commands |
| 423 |
-------------------- |
| 424 |
|
| 425 |
.. method:: exchange.declare(exchange_name, type, passive, |
| 426 |
durable, auto_delete, internal) |
| 427 |
|
| 428 |
Declares an exchange by name. |
| 429 |
|
| 430 |
See :meth:`amqp:Channel.exchange_declare <amqp.channel.Channel.exchange_declare>`. |
| 431 |
|
| 432 |
:keyword passive: Passive means the exchange won't be created, but you |
| 433 |
can use this to check if the exchange already exists. |
| 434 |
|
| 435 |
:keyword durable: Durable exchanges are persistent (i.e., they survive |
| 436 |
a broker restart). |
| 437 |
|
| 438 |
:keyword auto_delete: This means the exchange will be deleted by the broker |
| 439 |
when there are no more queues using it. |
| 440 |
|
| 441 |
|
| 442 |
.. method:: queue.declare(queue_name, passive, durable, exclusive, auto_delete) |
| 443 |
|
| 444 |
Declares a queue by name. |
| 445 |
|
| 446 |
See :meth:`amqp:Channel.queue_declare <amqp.channel.Channel.queue_declare>` |
| 447 |
|
| 448 |
Exclusive queues can only be consumed from by the current connection. |
| 449 |
Exclusive also implies `auto_delete`. |
| 450 |
|
| 451 |
.. method:: queue.bind(queue_name, exchange_name, routing_key) |
| 452 |
|
| 453 |
Binds a queue to an exchange with a routing key. |
| 454 |
|
| 455 |
Unbound queues won't receive messages, so this is necessary. |
| 456 |
|
| 457 |
See :meth:`amqp:Channel.queue_bind <amqp.channel.Channel.queue_bind>` |
| 458 |
|
| 459 |
.. method:: queue.delete(name, if_unused=False, if_empty=False) |
| 460 |
|
| 461 |
Deletes a queue and its binding. |
| 462 |
|
| 463 |
See :meth:`amqp:Channel.queue_delete <amqp.channel.Channel.queue_delete>` |
| 464 |
|
| 465 |
.. method:: exchange.delete(name, if_unused=False) |
| 466 |
|
| 467 |
Deletes an exchange. |
| 468 |
|
| 469 |
See :meth:`amqp:Channel.exchange_delete <amqp.channel.Channel.exchange_delete>` |
| 470 |
|
| 471 |
.. note:: |
| 472 |
|
| 473 |
Declaring doesn't necessarily mean "create". When you declare you |
| 474 |
*assert* that the entity exists and that it's operable. There's no |
| 475 |
rule as to whom should initially create the exchange/queue/binding, |
| 476 |
whether consumer or producer. Usually the first one to need it will |
| 477 |
be the one to create it. |
| 478 |
|
| 479 |
.. _amqp-api-hands-on: |
| 480 |
|
| 481 |
Hands-on with the API |
| 482 |
--------------------- |
| 483 |
|
| 484 |
Celery comes with a tool called :program:`celery amqp` |
| 485 |
that's used for command line access to the AMQP API, enabling access to |
| 486 |
administration tasks like creating/deleting queues and exchanges, purging |
| 487 |
queues or sending messages. It can also be used for non-AMQP brokers, |
| 488 |
but different implementation may not implement all commands. |
| 489 |
|
| 490 |
You can write commands directly in the arguments to :program:`celery amqp`, |
| 491 |
or just start with no arguments to start it in shell-mode: |
| 492 |
|
| 493 |
.. code-block:: console |
| 494 |
|
| 495 |
$ celery -A proj amqp |
| 496 |
-> connecting to amqp://guest@localhost:5672/. |
| 497 |
-> connected. |
| 498 |
1> |
| 499 |
|
| 500 |
Here ``1>`` is the prompt. The number 1, is the number of commands you |
| 501 |
have executed so far. Type ``help`` for a list of commands available. |
| 502 |
It also supports auto-completion, so you can start typing a command and then |
| 503 |
hit the `tab` key to show a list of possible matches. |
| 504 |
|
| 505 |
Let's create a queue you can send messages to: |
| 506 |
|
| 507 |
.. code-block:: console |
| 508 |
|
| 509 |
$ celery -A proj amqp |
| 510 |
1> exchange.declare testexchange direct |
| 511 |
ok. |
| 512 |
2> queue.declare testqueue |
| 513 |
ok. queue:testqueue messages:0 consumers:0. |
| 514 |
3> queue.bind testqueue testexchange testkey |
| 515 |
ok. |
| 516 |
|
| 517 |
This created the direct exchange ``testexchange``, and a queue |
| 518 |
named ``testqueue``. The queue is bound to the exchange using |
| 519 |
the routing key ``testkey``. |
| 520 |
|
| 521 |
From now on all messages sent to the exchange ``testexchange`` with routing |
| 522 |
key ``testkey`` will be moved to this queue. You can send a message by |
| 523 |
using the ``basic.publish`` command: |
| 524 |
|
| 525 |
.. code-block:: console |
| 526 |
|
| 527 |
4> basic.publish 'This is a message!' testexchange testkey |
| 528 |
ok. |
| 529 |
|
| 530 |
Now that the message is sent you can retrieve it again. You can use the |
| 531 |
``basic.get`` command here, that polls for new messages on the queue |
| 532 |
in a synchronous manner |
| 533 |
(this is OK for maintenance tasks, but for services you want to use |
| 534 |
``basic.consume`` instead) |
| 535 |
|
| 536 |
Pop a message off the queue: |
| 537 |
|
| 538 |
.. code-block:: console |
| 539 |
|
| 540 |
5> basic.get testqueue |
| 541 |
{'body': 'This is a message!', |
| 542 |
'delivery_info': {'delivery_tag': 1, |
| 543 |
'exchange': u'testexchange', |
| 544 |
'message_count': 0, |
| 545 |
'redelivered': False, |
| 546 |
'routing_key': u'testkey'}, |
| 547 |
'properties': {}} |
| 548 |
|
| 549 |
|
| 550 |
AMQP uses acknowledgment to signify that a message has been received |
| 551 |
and processed successfully. If the message hasn't been acknowledged |
| 552 |
and consumer channel is closed, the message will be delivered to |
| 553 |
another consumer. |
| 554 |
|
| 555 |
Note the delivery tag listed in the structure above; Within a connection |
| 556 |
channel, every received message has a unique delivery tag, |
| 557 |
This tag is used to acknowledge the message. Also note that |
| 558 |
delivery tags aren't unique across connections, so in another client |
| 559 |
the delivery tag `1` might point to a different message than in this channel. |
| 560 |
|
| 561 |
You can acknowledge the message you received using ``basic.ack``: |
| 562 |
|
| 563 |
.. code-block:: console |
| 564 |
|
| 565 |
6> basic.ack 1 |
| 566 |
ok. |
| 567 |
|
| 568 |
To clean up after our test session you should delete the entities you created: |
| 569 |
|
| 570 |
.. code-block:: console |
| 571 |
|
| 572 |
7> queue.delete testqueue |
| 573 |
ok. 0 messages deleted. |
| 574 |
8> exchange.delete testexchange |
| 575 |
ok. |
| 576 |
|
| 577 |
|
| 578 |
.. _routing-tasks: |
| 579 |
|
| 580 |
Routing Tasks |
| 581 |
============= |
| 582 |
|
| 583 |
.. _routing-defining-queues: |
| 584 |
|
| 585 |
Defining queues |
| 586 |
--------------- |
| 587 |
|
| 588 |
In Celery available queues are defined by the :setting:`task_queues` setting. |
| 589 |
|
| 590 |
Here's an example queue configuration with three queues; |
| 591 |
One for video, one for images, and one default queue for everything else: |
| 592 |
|
| 593 |
.. code-block:: python |
| 594 |
|
| 595 |
default_exchange = Exchange('default', type='direct') |
| 596 |
media_exchange = Exchange('media', type='direct') |
| 597 |
|
| 598 |
app.conf.task_queues = ( |
| 599 |
Queue('default', default_exchange, routing_key='default'), |
| 600 |
Queue('videos', media_exchange, routing_key='media.video'), |
| 601 |
Queue('images', media_exchange, routing_key='media.image') |
| 602 |
) |
| 603 |
app.conf.task_default_queue = 'default' |
| 604 |
app.conf.task_default_exchange = 'default' |
| 605 |
app.conf.task_default_routing_key = 'default' |
| 606 |
|
| 607 |
Here, the :setting:`task_default_queue` will be used to route tasks that |
| 608 |
doesn't have an explicit route. |
| 609 |
|
| 610 |
The default exchange, exchange type, and routing key will be used as the |
| 611 |
default routing values for tasks, and as the default values for entries |
| 612 |
in :setting:`task_queues`. |
| 613 |
|
| 614 |
Multiple bindings to a single queue are also supported. Here's an example |
| 615 |
of two routing keys that are both bound to the same queue: |
| 616 |
|
| 617 |
.. code-block:: python |
| 618 |
|
| 619 |
from kombu import Exchange, Queue, binding |
| 620 |
|
| 621 |
media_exchange = Exchange('media', type='direct') |
| 622 |
|
| 623 |
CELERY_QUEUES = ( |
| 624 |
Queue('media', [ |
| 625 |
binding(media_exchange, routing_key='media.video'), |
| 626 |
binding(media_exchange, routing_key='media.image'), |
| 627 |
]), |
| 628 |
) |
| 629 |
|
| 630 |
|
| 631 |
.. _routing-task-destination: |
| 632 |
|
| 633 |
Specifying task destination |
| 634 |
--------------------------- |
| 635 |
|
| 636 |
The destination for a task is decided by the following (in order): |
| 637 |
|
| 638 |
1. The routing arguments to :func:`Task.apply_async`. |
| 639 |
2. Routing related attributes defined on the :class:`~celery.app.task.Task` |
| 640 |
itself. |
| 641 |
3. The :ref:`routers` defined in :setting:`task_routes`. |
| 642 |
|
| 643 |
It's considered best practice to not hard-code these settings, but rather |
| 644 |
leave that as configuration options by using :ref:`routers`; |
| 645 |
This is the most flexible approach, but sensible defaults can still be set |
| 646 |
as task attributes. |
| 647 |
|
| 648 |
.. _routers: |
| 649 |
|
| 650 |
Routers |
| 651 |
------- |
| 652 |
|
| 653 |
A router is a function that decides the routing options for a task. |
| 654 |
|
| 655 |
All you need to define a new router is to define a function with |
| 656 |
the signature ``(name, args, kwargs, options, task=None, **kw)``: |
| 657 |
|
| 658 |
.. code-block:: python |
| 659 |
|
| 660 |
def route_task(name, args, kwargs, options, task=None, **kw): |
| 661 |
if name == 'myapp.tasks.compress_video': |
| 662 |
return {'exchange': 'video', |
| 663 |
'exchange_type': 'topic', |
| 664 |
'routing_key': 'video.compress'} |
| 665 |
|
| 666 |
If you return the ``queue`` key, it'll expand with the defined settings of |
| 667 |
that queue in :setting:`task_queues`: |
| 668 |
|
| 669 |
.. code-block:: javascript |
| 670 |
|
| 671 |
{'queue': 'video', 'routing_key': 'video.compress'} |
| 672 |
|
| 673 |
becomes --> |
| 674 |
|
| 675 |
.. code-block:: javascript |
| 676 |
|
| 677 |
{'queue': 'video', |
| 678 |
'exchange': 'video', |
| 679 |
'exchange_type': 'topic', |
| 680 |
'routing_key': 'video.compress'} |
| 681 |
|
| 682 |
|
| 683 |
You install router classes by adding them to the :setting:`task_routes` |
| 684 |
setting: |
| 685 |
|
| 686 |
.. code-block:: python |
| 687 |
|
| 688 |
task_routes = (route_task,) |
| 689 |
|
| 690 |
Router functions can also be added by name: |
| 691 |
|
| 692 |
.. code-block:: python |
| 693 |
|
| 694 |
task_routes = ('myapp.routers.route_task',) |
| 695 |
|
| 696 |
|
| 697 |
For simple task name -> route mappings like the router example above, |
| 698 |
you can simply drop a dict into :setting:`task_routes` to get the |
| 699 |
same behavior: |
| 700 |
|
| 701 |
.. code-block:: python |
| 702 |
|
| 703 |
task_routes = { |
| 704 |
'myapp.tasks.compress_video': { |
| 705 |
'queue': 'video', |
| 706 |
'routing_key': 'video.compress', |
| 707 |
}, |
| 708 |
} |
| 709 |
|
| 710 |
The routers will then be traversed in order, it will stop at the first router |
| 711 |
returning a true value, and use that as the final route for the task. |
| 712 |
|
| 713 |
You can also have multiple routers defined in a sequence: |
| 714 |
|
| 715 |
.. code-block:: python |
| 716 |
|
| 717 |
task_routes = [ |
| 718 |
route_task, |
| 719 |
{ |
| 720 |
'myapp.tasks.compress_video': { |
| 721 |
'queue': 'video', |
| 722 |
'routing_key': 'video.compress', |
| 723 |
}, |
| 724 |
] |
| 725 |
|
| 726 |
The routers will then be visited in turn, and the first to return |
| 727 |
a value will be chosen. |
| 728 |
|
| 729 |
If you\'re using Redis or RabbitMQ you can also specify the queue\'s default priority |
| 730 |
in the route. |
| 731 |
|
| 732 |
.. code-block:: python |
| 733 |
|
| 734 |
task_routes = { |
| 735 |
'myapp.tasks.compress_video': { |
| 736 |
'queue': 'video', |
| 737 |
'routing_key': 'video.compress', |
| 738 |
'priority': 10, |
| 739 |
}, |
| 740 |
} |
| 741 |
|
| 742 |
|
| 743 |
Similarly, calling `apply_async` on a task will override that |
| 744 |
default priority. |
| 745 |
|
| 746 |
.. code-block:: python |
| 747 |
|
| 748 |
task.apply_async(priority=0) |
| 749 |
|
| 750 |
|
| 751 |
.. admonition:: Priority Order and Cluster Responsiveness |
| 752 |
|
| 753 |
It is important to note that, due to worker prefetching, if a bunch of tasks |
| 754 |
submitted at the same time they may be out of priority order at first. |
| 755 |
Disabling worker prefetching will prevent this issue, but may cause less than |
| 756 |
ideal performance for small, fast tasks. In most cases, simply reducing |
| 757 |
`worker_prefetch_multiplier` to 1 is an easier and cleaner way to increase the |
| 758 |
responsiveness of your system without the costs of disabling prefetching |
| 759 |
entirely. |
| 760 |
|
| 761 |
Note that priorities values are sorted in reverse when |
| 762 |
using the redis broker: 0 being highest priority. |
| 763 |
|
| 764 |
|
| 765 |
Broadcast |
| 766 |
--------- |
| 767 |
|
| 768 |
Celery can also support broadcast routing. |
| 769 |
Here is an example exchange ``broadcast_tasks`` that delivers |
| 770 |
copies of tasks to all workers connected to it: |
| 771 |
|
| 772 |
.. code-block:: python |
| 773 |
|
| 774 |
from kombu.common import Broadcast |
| 775 |
|
| 776 |
app.conf.task_queues = (Broadcast('broadcast_tasks'),) |
| 777 |
app.conf.task_routes = { |
| 778 |
'tasks.reload_cache': { |
| 779 |
'queue': 'broadcast_tasks', |
| 780 |
'exchange': 'broadcast_tasks' |
| 781 |
} |
| 782 |
} |
| 783 |
|
| 784 |
Now the ``tasks.reload_cache`` task will be sent to every |
| 785 |
worker consuming from this queue. |
| 786 |
|
| 787 |
Here is another example of broadcast routing, this time with |
| 788 |
a :program:`celery beat` schedule: |
| 789 |
|
| 790 |
.. code-block:: python |
| 791 |
|
| 792 |
from kombu.common import Broadcast |
| 793 |
from celery.schedules import crontab |
| 794 |
|
| 795 |
app.conf.task_queues = (Broadcast('broadcast_tasks'),) |
| 796 |
|
| 797 |
app.conf.beat_schedule = { |
| 798 |
'test-task': { |
| 799 |
'task': 'tasks.reload_cache', |
| 800 |
'schedule': crontab(minute=0, hour='*/3'), |
| 801 |
'options': {'exchange': 'broadcast_tasks'} |
| 802 |
}, |
| 803 |
} |
| 804 |
|
| 805 |
|
| 806 |
.. admonition:: Broadcast & Results |
| 807 |
|
| 808 |
Note that Celery result doesn't define what happens if two |
| 809 |
tasks have the same task_id. If the same task is distributed to more |
| 810 |
than one worker, then the state history may not be preserved. |
| 811 |
|
| 812 |
It's a good idea to set the ``task.ignore_result`` attribute in |
| 813 |
this case. |