routing.rst 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355
  1. ===============
  2. Routing Tasks
  3. ===============
  4. **NOTE** This document refers to functionality only available in brokers
  5. using AMQP. Other brokers may implement some functionality, see their
  6. respective documenation for more information, or contact the `mailinglist`_.
  7. .. _`mailinglist`: http://groups.google.com/group/celery-users
  8. .. contents::
  9. :local:
  10. AMQP Primer
  11. ===========
  12. Messages
  13. --------
  14. A message consists of headers and a body. Celery uses headers to store
  15. the content type of the message and its content encoding. In Celery the
  16. content type is usually the serialization format used to serialize the
  17. message, and the body contains the name of the task to execute, the
  18. task id (UUID), the arguments to execute it with and some additional
  19. metadata - like the number of retries and its ETA (if any).
  20. This is an example task message represented as a Python dictionary:
  21. .. code-block:: python
  22. {"task": "myapp.tasks.add",
  23. "id":
  24. "args": [4, 4],
  25. "kwargs": {}}
  26. Producers, consumers and brokers
  27. --------------------------------
  28. The client sending messages is typically called a *publisher*, or
  29. a *producer*, while the entity receiving messages is called
  30. a *consumer*.
  31. The *broker* is the message server, routing messages from producers
  32. to consumers.
  33. You are likely to see these terms used a lot in AMQP related material.
  34. Exchanges, queues and routing keys.
  35. -----------------------------------
  36. 1. Messages are sent to exchanges.
  37. 2. An exchange routes messages to one or more queues. Several exchange types
  38. exists, providing different ways to do routing.
  39. 3. The message waits in the queue until someone consumes from it.
  40. 4. The message is deleted from the queue when it has been acknowledged.
  41. The steps required to send and receive messages are:
  42. 1. Create an exchange
  43. 2. Create a queue
  44. 3. Bind the queue to the exchange.
  45. Celery automatically creates the entities necessary for the queues in
  46. ``CELERY_QUEUES`` to work (except if the queue's ``auto_declare`` setting
  47. is set to :const:`False`).
  48. Here's an example queue configuration with three queues;
  49. One for video, one for images and finally, one default queue for everything else:
  50. .. code-block:: python
  51. CELERY_QUEUES = {
  52. "default": {
  53. "exchange": "default",
  54. "binding_key": "default"},
  55. "videos": {
  56. "exchange": "media",
  57. "binding_key": "media.video",
  58. },
  59. "images": {
  60. "exchange": "media",
  61. "binding_key": "media.image",
  62. }
  63. }
  64. CELERY_DEFAULT_QUEUE = "default"
  65. CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
  66. CELERY_DEFAULT_ROUTING_KEY = "default"
  67. **NOTE**: In Celery the ``routing_key`` is the key used to send the message,
  68. while ``binding_key`` is the key the queue is bound with. In the AMQP API
  69. they are both referred to as the routing key.
  70. Exchange types
  71. --------------
  72. The exchange type defines how the messages are routed through the exchange.
  73. The exchange types defined in the standard are ``direct``, ``topic``,
  74. ``fanout`` and ``headers``. Also non-standard exchange types are available
  75. as plugins to RabbitMQ, like the `last-value-cache plug-in`_ by Michael
  76. Bridgen.
  77. .. _`last-value-cache plug-in`:
  78. http://github.com/squaremo/rabbitmq-lvc-plugin
  79. Direct exchanges
  80. ~~~~~~~~~~~~~~~~
  81. Direct exchanges match by exact routing keys, so a queue bound with
  82. the routing key ``video`` only receives messages with the same routing key.
  83. Topic exchanges
  84. ~~~~~~~~~~~~~~~
  85. Topic exchanges matches routing keys using dot-separated words, and can
  86. include wildcard characters: ``*`` matches a single word, ``#`` matches
  87. zero or more words.
  88. With routing keys like ``usa.news``, ``usa.weather``, ``norway.news`` and
  89. ``norway.weather``, bindings could be ``*.news`` (all news), ``usa.#`` (all
  90. items in the USA) or ``usa.weather`` (all USA weather items).
  91. Related API commands
  92. --------------------
  93. exchange.declare(exchange_name, type, passive, durable, auto_delete, internal)
  94. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  95. Declares an exchange by name.
  96. * ``passive`` means the exchange won't be created, but you can use this to
  97. check if the exchange already exists.
  98. * Durable exchanges are persistent. That is - they survive a broker restart.
  99. * ``auto_delete`` means the queue will be deleted by the broker when there
  100. are no more queues using it.
  101. queue.declare(queue_name, passive, durable, exclusive, auto_delete)
  102. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  103. Declares a queue by name.
  104. * exclusive queues can only be consumed from by the current connection.
  105. implies ``auto_delete``.
  106. queue.bind(queue_name, exchange_name, routing_key)
  107. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  108. Binds a queue to an exchange with a routing key.
  109. Unbound queues will not receive messages, so this is necessary.
  110. queue.delete(name, if_unused, if_empty)
  111. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  112. Deletes a queue and its binding.
  113. exchange.delete(name, if_unused)
  114. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  115. Deletes an exchange.
  116. **NOTE**: Declaring does not necessarily mean "create". When you declare you
  117. *assert* that the entity exists and that it's operable. There is no rule as to
  118. whom should initially create the exchange/queue/binding, whether consumer
  119. or producer. Usually the first one to need it will be the one to create it.
  120. Hands-on with the API
  121. ---------------------
  122. Celery comes with a tool called ``camqadm`` (short for celery AMQP admin).
  123. It's used for simple admnistration tasks like creating/deleting queues and
  124. exchanges, purging queues and sending messages. In short it's for simple
  125. command-line access to the AMQP API.
  126. You can write commands directly in the arguments to ``camqadm``, or just start
  127. with no arguments to start it in shell-mode::
  128. $ camqadm
  129. -> connecting to amqp://guest@localhost:5672/.
  130. -> connected.
  131. 1>
  132. Here ``1>`` is the prompt. The number is counting the number of commands you
  133. have executed. Type ``help`` for a list of commands. It also has
  134. autocompletion, so you can start typing a command and then hit the
  135. ``tab`` key to show a list of possible matches.
  136. Now let's create a queue we can send messages to::
  137. 1> exchange.declare testexchange direct
  138. ok.
  139. 2> queue.declare testqueue
  140. ok. queue:testqueue messages:0 consumers:0.
  141. 3> queue.bind testqueue testexchange testkey
  142. ok.
  143. This created the direct exchange ``testexchange``, and a queue
  144. named ``testqueue``. The queue is bound to the exchange using
  145. the routing key ``testkey``.
  146. From now on all messages sent to the exchange ``testexchange`` with routing
  147. key ``testkey`` will be moved to this queue. We can send a message by
  148. using the ``basic.publish`` command::
  149. 4> basic.publish "This is a message!" testexchange testkey
  150. ok.
  151. Now that the message is sent we can retrieve it again. We use the
  152. ``basic.get`` command here, which pops a single message off the queue,
  153. this command is not recommended for production as it implies polling, any
  154. real application would declare consumers instead.
  155. Pop a message off the queue::
  156. 5> basic.get testqueue
  157. {'body': 'This is a message!',
  158. 'delivery_info': {'delivery_tag': 1,
  159. 'exchange': u'testexchange',
  160. 'message_count': 0,
  161. 'redelivered': False,
  162. 'routing_key': u'testkey'},
  163. 'properties': {}}
  164. AMQP uses acknowledgment to signify that a message has been received
  165. and processed successfully. The message is sent to the next receiver
  166. if it has not been acknowledged before the client connection is closed.
  167. Note the delivery tag listed in the structure above; Within a connection channel,
  168. every received message has a unique delivery tag,
  169. This tag is used to acknowledge the message. Note that
  170. delivery tags are not unique across connections, so in another client
  171. the delivery tag ``1`` might point to a different message than in this channel.
  172. You can acknowledge the message we received using ``basic.ack``::
  173. 6> basic.ack 1
  174. ok.
  175. To clean up after our test session we should delete the entities we created::
  176. 7> queue.delete testqueue
  177. ok. 0 messages deleted.
  178. 8> exchange.delete testexchange
  179. ok.
  180. Routing Tasks
  181. =============
  182. Defining queues
  183. ---------------
  184. In Celery the queues are defined by the ``CELERY_QUEUES`` setting.
  185. Here's an example queue configuration with three queues;
  186. One for video, one for images and finally, one default queue for everything else:
  187. .. code-block:: python
  188. CELERY_QUEUES = {
  189. "default": {
  190. "exchange": "default",
  191. "binding_key": "default"},
  192. "videos": {
  193. "exchange": "media",
  194. "exchange_type": "topic",
  195. "binding_key": "media.video",
  196. },
  197. "images": {
  198. "exchange": "media",
  199. "exchange_type": "topic",
  200. "binding_key": "media.image",
  201. }
  202. }
  203. CELERY_DEFAULT_QUEUE = "default"
  204. CELERY_DEFAULT_EXCHANGE = "default"
  205. CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
  206. CELERY_DEFAULT_ROUTING_KEY = "default"
  207. Here, the ``CELERY_DEFAULT_QUEUE`` will be used to route tasks that doesn't
  208. have an explicit route.
  209. THe default exchange, exchange type and routing key, will be used as the
  210. default routing values for tasks, and as the default values for entries
  211. in ``CELERY_QUEUES``.
  212. Specifying task destination
  213. ---------------------------
  214. The destination for a task is decided by the following (in order):
  215. # The :ref:`routers` defined in ``CELERY_ROUTES``.
  216. # The routing arguments to :func:`~celery.execute.apply_async`.
  217. # Routing related attributes defined on the :class:`~celery.task.base.Task` itself.
  218. It is considered best practice to not hard-code these settings, but rather
  219. leave that as an configuration option by using :ref:`routers`.
  220. This is the most flexible approach, but sensible defaults can still be set
  221. as task attributes.
  222. .. _routers:
  223. Routers
  224. -------
  225. A router is a class that decides the routing options for a task.
  226. All you need to define a new router, is to create a class with a
  227. ``route_for_task`` method:
  228. .. code-block:: python
  229. class MyRouter(object):
  230. def route_for_task(task, task_id=None, args=None, kwargs=None):
  231. if task == "myapp.tasks.compress_video":
  232. return {"exchange": "video",
  233. "exchange_type": "topic",
  234. "routing_key": "video.compress"}
  235. If you return the ``queue`` key, it will expand with the defined settings of
  236. that queue in ``CELERY_QUEUES``::
  237. {"queue": "video", "routing_key": "video.compress"}
  238. becomes -->
  239. {"queue": "video",
  240. "exchange": "video",
  241. "exchange_type": "topic",
  242. "routing_key": "video.compress"}
  243. You install router classes by adding it to the ``CELERY_ROUTES`` setting::
  244. CELERY_ROUTES = (MyRouter, )
  245. Router classes can also be added by name::
  246. CELERY_ROUTES = ("myapp.routers.MyRouter", )
  247. For simple task name -> route mappings, like the router example above, you can simply
  248. drop a dict into ``CELERY_ROUTES`` to get the same result::
  249. CELERY_ROUTES = ({"myapp.tasks.compress_video": {
  250. "queue": "video",
  251. "routing_key": "video.compress"}}, )
  252. The routers will then be traversed in order, it will stop at the first router
  253. returning a value and use that as the final route for the task.