routing.rst 17 KB

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