routing.rst 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682
  1. .. _guide-routing:
  2. ===============
  3. Routing Tasks
  4. ===============
  5. .. note::
  6. Alternate routing concepts like topic and fanout may not be
  7. available for all transports, please consult the
  8. :ref:`transport comparison table <kombu:transport-comparison>`.
  9. .. contents::
  10. :local:
  11. .. _routing-basics:
  12. Basics
  13. ======
  14. .. _routing-automatic:
  15. Automatic routing
  16. -----------------
  17. The simplest way to do routing is to use the
  18. :setting:`task_create_missing_queues` setting (on by default).
  19. With this setting on, a named queue that is not already defined in
  20. :setting:`task_queues` will be created automatically. This makes it easy to
  21. perform simple routing tasks.
  22. Say you have two servers, `x`, and `y` that handles regular tasks,
  23. and one server `z`, that only handles feed related tasks. You can use this
  24. configuration::
  25. task_routes = {'feed.tasks.import_feed': {'queue': 'feeds'}}
  26. With this route enabled import feed tasks will be routed to the
  27. `"feeds"` queue, while all other tasks will be routed to the default queue
  28. (named `"celery"` for historical reasons).
  29. Alternatively, you can use glob pattern matching, or even regular expressions,
  30. to match all tasks in the ``feed.tasks`` name-space:
  31. .. code-block:: python
  32. app.conf.task_routes = {'feed.tasks.*': {'queue': 'feeds'}}
  33. If the order in which the patterns are matched is important you should should
  34. specify a tuple as the task router instead::
  35. task_routes = ([
  36. ('feed.tasks.*': {'queue': 'feeds'}),
  37. ('web.tasks.*': {'queue': 'web'}),
  38. (re.compile(r'(video|image)\.tasks\..*'), {'queue': 'media'}),
  39. ],)
  40. .. note::
  41. The :setting:`task_routes` setting can either be a dictionary, or a
  42. list of router objects, so in this case we need to specify the setting
  43. as a tuple containing a list.
  44. After installing the router, you can start server `z` to only process the feeds
  45. queue like this:
  46. .. code-block:: console
  47. user@z:/$ celery -A proj worker -Q feeds
  48. You can specify as many queues as you want, so you can make this server
  49. process the default queue as well:
  50. .. code-block:: console
  51. user@z:/$ celery -A proj worker -Q feeds,celery
  52. .. _routing-changing-default-queue:
  53. Changing the name of the default queue
  54. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  55. You can change the name of the default queue by using the following
  56. configuration:
  57. .. code-block:: python
  58. from kombu import Exchange, Queue
  59. app.conf.task_default_queue = 'default'
  60. app.conf.task_queues = (
  61. Queue('default', Exchange('default'), routing_key='default'),
  62. )
  63. .. _routing-autoqueue-details:
  64. How the queues are defined
  65. ~~~~~~~~~~~~~~~~~~~~~~~~~~
  66. The point with this feature is to hide the complex AMQP protocol for users
  67. with only basic needs. However -- you may still be interested in how these queues
  68. are declared.
  69. A queue named `"video"` will be created with the following settings:
  70. .. code-block:: javascript
  71. {'exchange': 'video',
  72. 'exchange_type': 'direct',
  73. 'routing_key': 'video'}
  74. The non-AMQP transports like `SQS` do not support exchanges,
  75. so they require the exchange to have the same name as the queue. Using this
  76. design ensures it will work for them as well.
  77. .. _routing-manual:
  78. Manual routing
  79. --------------
  80. Say you have two servers, `x`, and `y` that handles regular tasks,
  81. and one server `z`, that only handles feed related tasks, you can use this
  82. configuration:
  83. .. code-block:: python
  84. from kombu import Queue
  85. app.conf.task_default_queue = 'default'
  86. app.conf.task_queues = (
  87. Queue('default', routing_key='task.#'),
  88. Queue('feed_tasks', routing_key='feed.#'),
  89. )
  90. task_default_exchange = 'tasks'
  91. task_default_exchange_type = 'topic'
  92. task_default_routing_key = 'task.default'
  93. :setting:`task_queues` is a list of :class:`~kombu.entitity.Queue`
  94. instances.
  95. If you don't set the exchange or exchange type values for a key, these
  96. will be taken from the :setting:`task_default_exchange` and
  97. :setting:`task_default_exchange_type` settings.
  98. To route a task to the `feed_tasks` queue, you can add an entry in the
  99. :setting:`task_routes` setting:
  100. .. code-block:: python
  101. task_routes = {
  102. 'feeds.tasks.import_feed': {
  103. 'queue': 'feed_tasks',
  104. 'routing_key': 'feed.import',
  105. },
  106. }
  107. You can also override this using the `routing_key` argument to
  108. :meth:`Task.apply_async`, or :func:`~celery.execute.send_task`:
  109. >>> from feeds.tasks import import_feed
  110. >>> import_feed.apply_async(args=['http://cnn.com/rss'],
  111. ... queue='feed_tasks',
  112. ... routing_key='feed.import')
  113. To make server `z` consume from the feed queue exclusively you can
  114. start it with the :option:`celery worker -Q` option:
  115. .. code-block:: console
  116. user@z:/$ celery -A proj worker -Q feed_tasks --hostname=z@%h
  117. Servers `x` and `y` must be configured to consume from the default queue:
  118. .. code-block:: console
  119. user@x:/$ celery -A proj worker -Q default --hostname=x@%h
  120. user@y:/$ celery -A proj worker -Q default --hostname=y@%h
  121. If you want, you can even have your feed processing worker handle regular
  122. tasks as well, maybe in times when there's a lot of work to do:
  123. .. code-block:: console
  124. user@z:/$ celery -A proj worker -Q feed_tasks,default --hostname=z@%h
  125. If you have another queue but on another exchange you want to add,
  126. just specify a custom exchange and exchange type:
  127. .. code-block:: python
  128. from kombu import Exchange, Queue
  129. app.conf.task_queues = (
  130. Queue('feed_tasks', routing_key='feed.#'),
  131. Queue('regular_tasks', routing_key='task.#'),
  132. Queue('image_tasks', exchange=Exchange('mediatasks', type='direct'),
  133. routing_key='image.compress'),
  134. )
  135. If you're confused about these terms, you should read up on AMQP.
  136. .. seealso::
  137. In addition to the :ref:`amqp-primer` below, there's
  138. `Rabbits and Warrens`_, an excellent blog post describing queues and
  139. exchanges. There's also AMQP in 10 minutes*: `Flexible Routing Model`_,
  140. and `Standard Exchange Types`_. For users of RabbitMQ the `RabbitMQ FAQ`_
  141. could be useful as a source of information.
  142. .. _`Rabbits and Warrens`: http://blogs.digitar.com/jjww/2009/01/rabbits-and-warrens/
  143. .. _`Flexible Routing Model`: http://bit.ly/95XFO1
  144. .. _`Standard Exchange Types`: http://bit.ly/EEWca
  145. .. _`RabbitMQ FAQ`: http://www.rabbitmq.com/faq.html
  146. .. _routing-special_options:
  147. Special Routing Options
  148. =======================
  149. .. _routing-options-rabbitmq-priorities:
  150. RabbitMQ Message Priorities
  151. ---------------------------
  152. :supported transports: RabbitMQ
  153. .. versionadded:: 4.0
  154. Queues can be configured to support priorities by setting the
  155. ``x-max-priority`` argument:
  156. .. code-block:: python
  157. from kombu import Exchange, Queue
  158. app.conf.task_queues = [
  159. Queue('tasks', Exchange('tasks'), routing_key='tasks',
  160. queue_arguments={'x-max-priority': 10},
  161. ]
  162. A default value for all queues can be set using the
  163. :setting:`task_queue_max_priority` setting:
  164. .. code-block:: python
  165. app.conf.task_queue_max_priority = 10
  166. .. _amqp-primer:
  167. AMQP Primer
  168. ===========
  169. Messages
  170. --------
  171. A message consists of headers and a body. Celery uses headers to store
  172. the content type of the message and its content encoding. The
  173. content type is usually the serialization format used to serialize the
  174. message. The body contains the name of the task to execute, the
  175. task id (UUID), the arguments to apply it with and some additional
  176. meta-data -- like the number of retries or an ETA.
  177. This is an example task message represented as a Python dictionary:
  178. .. code-block:: javascript
  179. {'task': 'myapp.tasks.add',
  180. 'id': '54086c5e-6193-4575-8308-dbab76798756',
  181. 'args': [4, 4],
  182. 'kwargs': {}}
  183. .. _amqp-producers-consumers-brokers:
  184. Producers, consumers and brokers
  185. --------------------------------
  186. The client sending messages is typically called a *publisher*, or
  187. a *producer*, while the entity receiving messages is called
  188. a *consumer*.
  189. The *broker* is the message server, routing messages from producers
  190. to consumers.
  191. You are likely to see these terms used a lot in AMQP related material.
  192. .. _amqp-exchanges-queues-keys:
  193. Exchanges, queues and routing keys.
  194. -----------------------------------
  195. 1. Messages are sent to exchanges.
  196. 2. An exchange routes messages to one or more queues. Several exchange types
  197. exists, providing different ways to do routing, or implementing
  198. different messaging scenarios.
  199. 3. The message waits in the queue until someone consumes it.
  200. 4. The message is deleted from the queue when it has been acknowledged.
  201. The steps required to send and receive messages are:
  202. 1. Create an exchange
  203. 2. Create a queue
  204. 3. Bind the queue to the exchange.
  205. Celery automatically creates the entities necessary for the queues in
  206. :setting:`task_queues` to work (except if the queue's `auto_declare`
  207. setting is set to :const:`False`).
  208. Here's an example queue configuration with three queues;
  209. One for video, one for images and one default queue for everything else:
  210. .. code-block:: python
  211. from kombu import Exchange, Queue
  212. app.conf.task_queues = (
  213. Queue('default', Exchange('default'), routing_key='default'),
  214. Queue('videos', Exchange('media'), routing_key='media.video'),
  215. Queue('images', Exchange('media'), routing_key='media.image'),
  216. )
  217. app.conf.task_default_queue = 'default'
  218. app.conf.task_default_exchange_type = 'direct'
  219. app.conf.task_default_routing_key = 'default'
  220. .. _amqp-exchange-types:
  221. Exchange types
  222. --------------
  223. The exchange type defines how the messages are routed through the exchange.
  224. The exchange types defined in the standard are `direct`, `topic`,
  225. `fanout` and `headers`. Also non-standard exchange types are available
  226. as plug-ins to RabbitMQ, like the `last-value-cache plug-in`_ by Michael
  227. Bridgen.
  228. .. _`last-value-cache plug-in`:
  229. https://github.com/squaremo/rabbitmq-lvc-plugin
  230. .. _amqp-exchange-type-direct:
  231. Direct exchanges
  232. ~~~~~~~~~~~~~~~~
  233. Direct exchanges match by exact routing keys, so a queue bound by
  234. the routing key `video` only receives messages with that routing key.
  235. .. _amqp-exchange-type-topic:
  236. Topic exchanges
  237. ~~~~~~~~~~~~~~~
  238. Topic exchanges matches routing keys using dot-separated words, and the
  239. wild-card characters: ``*`` (matches a single word), and ``#`` (matches
  240. zero or more words).
  241. With routing keys like ``usa.news``, ``usa.weather``, ``norway.news`` and
  242. ``norway.weather``, bindings could be ``*.news`` (all news), ``usa.#`` (all
  243. items in the USA) or ``usa.weather`` (all USA weather items).
  244. .. _amqp-api:
  245. Related API commands
  246. --------------------
  247. .. method:: exchange.declare(exchange_name, type, passive,
  248. durable, auto_delete, internal)
  249. Declares an exchange by name.
  250. See :meth:`amqp:Channel.exchange_declare <amqp.channel.Channel.exchange_declare>`.
  251. :keyword passive: Passive means the exchange won't be created, but you
  252. can use this to check if the exchange already exists.
  253. :keyword durable: Durable exchanges are persistent. That is - they survive
  254. a broker restart.
  255. :keyword auto_delete: This means the queue will be deleted by the broker
  256. when there are no more queues using it.
  257. .. method:: queue.declare(queue_name, passive, durable, exclusive, auto_delete)
  258. Declares a queue by name.
  259. See :meth:`amqp:Channel.queue_declare <amqp.channel.Channel.queue_declare>`
  260. Exclusive queues can only be consumed from by the current connection.
  261. Exclusive also implies `auto_delete`.
  262. .. method:: queue.bind(queue_name, exchange_name, routing_key)
  263. Binds a queue to an exchange with a routing key.
  264. Unbound queues will not receive messages, so this is necessary.
  265. See :meth:`amqp:Channel.queue_bind <amqp.channel.Channel.queue_bind>`
  266. .. method:: queue.delete(name, if_unused=False, if_empty=False)
  267. Deletes a queue and its binding.
  268. See :meth:`amqp:Channel.queue_delete <amqp.channel.Channel.queue_delete>`
  269. .. method:: exchange.delete(name, if_unused=False)
  270. Deletes an exchange.
  271. See :meth:`amqp:Channel.exchange_delete <amqp.channel.Channel.exchange_delete>`
  272. .. note::
  273. Declaring does not necessarily mean "create". When you declare you
  274. *assert* that the entity exists and that it's operable. There is no
  275. rule as to whom should initially create the exchange/queue/binding,
  276. whether consumer or producer. Usually the first one to need it will
  277. be the one to create it.
  278. .. _amqp-api-hands-on:
  279. Hands-on with the API
  280. ---------------------
  281. Celery comes with a tool called :program:`celery amqp`
  282. that is used for command line access to the AMQP API, enabling access to
  283. administration tasks like creating/deleting queues and exchanges, purging
  284. queues or sending messages. It can also be used for non-AMQP brokers,
  285. but different implementation may not implement all commands.
  286. You can write commands directly in the arguments to :program:`celery amqp`,
  287. or just start with no arguments to start it in shell-mode:
  288. .. code-block:: console
  289. $ celery -A proj amqp
  290. -> connecting to amqp://guest@localhost:5672/.
  291. -> connected.
  292. 1>
  293. Here ``1>`` is the prompt. The number 1, is the number of commands you
  294. have executed so far. Type ``help`` for a list of commands available.
  295. It also supports auto-completion, so you can start typing a command and then
  296. hit the `tab` key to show a list of possible matches.
  297. Let's create a queue you can send messages to:
  298. .. code-block:: console
  299. $ celery -A proj amqp
  300. 1> exchange.declare testexchange direct
  301. ok.
  302. 2> queue.declare testqueue
  303. ok. queue:testqueue messages:0 consumers:0.
  304. 3> queue.bind testqueue testexchange testkey
  305. ok.
  306. This created the direct exchange ``testexchange``, and a queue
  307. named ``testqueue``. The queue is bound to the exchange using
  308. the routing key ``testkey``.
  309. From now on all messages sent to the exchange ``testexchange`` with routing
  310. key ``testkey`` will be moved to this queue. You can send a message by
  311. using the ``basic.publish`` command:
  312. .. code-block:: console
  313. 4> basic.publish 'This is a message!' testexchange testkey
  314. ok.
  315. Now that the message is sent you can retrieve it again. You can use the
  316. ``basic.get``` command here, which polls for new messages on the queue
  317. (which is alright for maintenance tasks, for services you'd want to use
  318. ``basic.consume`` instead)
  319. Pop a message off the queue:
  320. .. code-block:: console
  321. 5> basic.get testqueue
  322. {'body': 'This is a message!',
  323. 'delivery_info': {'delivery_tag': 1,
  324. 'exchange': u'testexchange',
  325. 'message_count': 0,
  326. 'redelivered': False,
  327. 'routing_key': u'testkey'},
  328. 'properties': {}}
  329. AMQP uses acknowledgment to signify that a message has been received
  330. and processed successfully. If the message has not been acknowledged
  331. and consumer channel is closed, the message will be delivered to
  332. another consumer.
  333. Note the delivery tag listed in the structure above; Within a connection
  334. channel, every received message has a unique delivery tag,
  335. This tag is used to acknowledge the message. Also note that
  336. delivery tags are not unique across connections, so in another client
  337. the delivery tag `1` might point to a different message than in this channel.
  338. You can acknowledge the message you received using ``basic.ack``:
  339. .. code-block:: console
  340. 6> basic.ack 1
  341. ok.
  342. To clean up after our test session you should delete the entities you created:
  343. .. code-block:: console
  344. 7> queue.delete testqueue
  345. ok. 0 messages deleted.
  346. 8> exchange.delete testexchange
  347. ok.
  348. .. _routing-tasks:
  349. Routing Tasks
  350. =============
  351. .. _routing-defining-queues:
  352. Defining queues
  353. ---------------
  354. In Celery available queues are defined by the :setting:`task_queues` setting.
  355. Here's an example queue configuration with three queues;
  356. One for video, one for images and one default queue for everything else:
  357. .. code-block:: python
  358. default_exchange = Exchange('default', type='direct')
  359. media_exchange = Exchange('media', type='direct')
  360. app.conf.task_queues = (
  361. Queue('default', default_exchange, routing_key='default'),
  362. Queue('videos', media_exchange, routing_key='media.video'),
  363. Queue('images', media_exchange, routing_key='media.image')
  364. )
  365. app.conf.task_default_queue = 'default'
  366. app.conf.task_default_exchange = 'default'
  367. app.conf.task_default_routing_key = 'default'
  368. Here, the :setting:`task_default_queue` will be used to route tasks that
  369. doesn't have an explicit route.
  370. The default exchange, exchange type and routing key will be used as the
  371. default routing values for tasks, and as the default values for entries
  372. in :setting:`task_queues`.
  373. .. _routing-task-destination:
  374. Specifying task destination
  375. ---------------------------
  376. The destination for a task is decided by the following (in order):
  377. 1. The :ref:`routers` defined in :setting:`task_routes`.
  378. 2. The routing arguments to :func:`Task.apply_async`.
  379. 3. Routing related attributes defined on the :class:`~celery.task.base.Task`
  380. itself.
  381. It is considered best practice to not hard-code these settings, but rather
  382. leave that as configuration options by using :ref:`routers`;
  383. This is the most flexible approach, but sensible defaults can still be set
  384. as task attributes.
  385. .. _routers:
  386. Routers
  387. -------
  388. A router is a class that decides the routing options for a task.
  389. All you need to define a new router is to create a class with a
  390. ``route_for_task`` method:
  391. .. code-block:: python
  392. class MyRouter(object):
  393. def route_for_task(self, task, args=None, kwargs=None):
  394. if task == 'myapp.tasks.compress_video':
  395. return {'exchange': 'video',
  396. 'exchange_type': 'topic',
  397. 'routing_key': 'video.compress'}
  398. return None
  399. If you return the ``queue`` key, it will expand with the defined settings of
  400. that queue in :setting:`task_queues`:
  401. .. code-block:: javascript
  402. {'queue': 'video', 'routing_key': 'video.compress'}
  403. becomes -->
  404. .. code-block:: javascript
  405. {'queue': 'video',
  406. 'exchange': 'video',
  407. 'exchange_type': 'topic',
  408. 'routing_key': 'video.compress'}
  409. You install router classes by adding them to the :setting:`task_routes`
  410. setting:
  411. .. code-block:: python
  412. task_routes = (MyRouter(),)
  413. Router classes can also be added by name:
  414. .. code-block:: python
  415. task_routes = ('myapp.routers.MyRouter',)
  416. For simple task name -> route mappings like the router example above,
  417. you can simply drop a dict into :setting:`task_routes` to get the
  418. same behavior:
  419. .. code-block:: python
  420. task_routes = (
  421. {'myapp.tasks.compress_video': {
  422. 'queue': 'video',
  423. 'routing_key': 'video.compress',
  424. }},
  425. )
  426. The routers will then be traversed in order, it will stop at the first router
  427. returning a true value, and use that as the final route for the task.
  428. Broadcast
  429. ---------
  430. Celery can also support broadcast routing.
  431. Here is an example exchange ``broadcast_tasks`` that delivers
  432. copies of tasks to all workers connected to it:
  433. .. code-block:: python
  434. from kombu.common import Broadcast
  435. app.conf.task_queues = (Broadcast('broadcast_tasks'),)
  436. app.conf.task_routes = {'tasks.reload_cache': {'queue': 'broadcast_tasks'}}
  437. Now the ``tasks.reload_cache`` task will be sent to every
  438. worker consuming from this queue.
  439. Here is another example of broadcast routing, this time with
  440. a :program:`celery beat` schedule:
  441. .. code-block:: python
  442. from kombu.common import Broadcast
  443. from celery.schedules import crontab
  444. app.conf.task_queues = (Broadcast('broadcast_tasks'),)
  445. app.conf.beat_schedule = {
  446. 'test-task': {
  447. 'task': 'tasks.reload_cache',
  448. 'schedule': crontab(minute=0, hour='*/3'),
  449. 'options': {'exchange': 'broadcast_tasks'}
  450. },
  451. }
  452. .. admonition:: Broadcast & Results
  453. Note that Celery result does not define what happens if two
  454. tasks have the same task_id. If the same task is distributed to more
  455. than one worker, then the state history may not be preserved.
  456. It is a good idea to set the ``task.ignore_result`` attribute in
  457. this case.