routing.rst 17 KB

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