routing.rst 8.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249
  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. TODO Mindblowing one-line simple explanation here. TODO
  37. 1. Messages are sent to exchanges.
  38. 2. An exchange routes messages to one or more queues. Several exchange types
  39. exists, providing different ways to do routing.
  40. 3. The message waits in the queue until someone consumes from it.
  41. 4. The message is deleted from the queue when it has been acknowledged.
  42. The steps required to send and receive messages are:
  43. 1. Create an exchange
  44. 2. Create a queue
  45. 3. Bind the queue to the exchange.
  46. Celery automatically creates the entities necessary for the queues in
  47. ``CELERY_QUEUES`` to work (unless the queue's ``auto_declare`` setting
  48. is set)
  49. Here's an example queue configuration with three queues;
  50. One for video, one for images and one default queue for everything else:
  51. .. code-block:: python
  52. CELERY_QUEUES = {
  53. "default": {
  54. "exchange": "default",
  55. "binding_key": "default"},
  56. "videos": {
  57. "exchange": "media",
  58. "binding_key": "media.video",
  59. },
  60. "images": {
  61. "exchange": "media",
  62. "binding_key": "media.image",
  63. }
  64. }
  65. CELERY_DEFAULT_QUEUE = "default"
  66. CELERY_DEFAULT_EXCHANGE_TYPE = "direct"
  67. CELERY_DEFAULT_ROUTING_KEY = "default"
  68. **NOTE**: In Celery the ``routing_key`` is the key used to send the message,
  69. while ``binding_key`` is the key the queue is bound with. In the AMQP API
  70. they are both referred to as a routing key.
  71. Exchange types
  72. --------------
  73. The exchange type defines how the messages are routed through the exchange.
  74. The exchange types defined in the standard are ``direct``, ``topic``,
  75. ``fanout`` and ``headers``. Also non-standard exchange types are available
  76. as plugins to RabbitMQ, like the `last-value-cache plug-in`_ by Michael
  77. Bridgen.
  78. .. _`last-value-cache plug-in`:
  79. http://github.com/squaremo/rabbitmq-lvc-plugin
  80. Direct exchanges
  81. ~~~~~~~~~~~~~~~~
  82. Direct exchanges match by exact routing keys, so a queue bound with
  83. the routing key ``video`` only receives messages with the same routing key.
  84. Topic exchanges
  85. ~~~~~~~~~~~~~~~
  86. Topic exchanges matches routing keys using dot-separated words, and can
  87. include wildcard characters: ``*`` matches a single word, ``#`` matches
  88. zero or more words.
  89. With routing keys like ``usa.news``, ``usa.weather``, ``norway.news`` and
  90. ``norway.weather``, bindings could be ``*.news`` (all news), ``usa.#`` (all
  91. items in the USA) or ``usa.weather`` (all USA weather items).
  92. Related API commands
  93. --------------------
  94. exchange.declare(exchange_name, type, passive, durable, auto_delete, internal)
  95. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  96. Declares an exchange by name.
  97. * ``passive`` means the exchange won't be created, but you can use this to
  98. check if the exchange already exists.
  99. * Durable exchanges are persistent. That is - they survive a broker restart.
  100. * ``auto_delete`` means the queue will be deleted by the broker when there
  101. are no more queues using it.
  102. queue.declare(queue_name, passive, durable, exclusive, auto_delete)
  103. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  104. Declares a queue by name.
  105. * exclusive queues can only be consumed from by the current connection.
  106. implies ``auto_delete``.
  107. queue.bind(queue_name, exchange_name, routing_key)
  108. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  109. Binds a queue to an exchange with a routing key.
  110. Unbound queues will not receive messages, so this is necessary.
  111. queue.delete(name, if_unused, if_empty)
  112. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  113. Deletes a queue and its binding.
  114. exchange.delete(name, if_unused)
  115. ~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~~
  116. Deletes an exchange.
  117. **NOTE**: Declaring does not necessarily mean "create". When you declare you
  118. *assert* that the entity exists and that it's operable. There is no rule as to
  119. whom should initially create the exchange/queue/binding, whether consumer
  120. or producer. Usually the first one to need it will be the one to create it.
  121. Hands-on with the API
  122. ---------------------
  123. Celery comes with a tool called ``camqadm`` (short for celery AMQP admin).
  124. It's used for simple admnistration tasks like creating/deleting queues and
  125. exchanges, purging queues and sending messages. In short it's for simple
  126. command-line access to the AMQP API.
  127. You can write commands directly in the arguments to ``camqadm``, or just start
  128. with no arguments to start it in shell-mode::
  129. $ camqadm
  130. -> connecting to amqp://guest@localhost:5672/.
  131. -> connected.
  132. 1>
  133. Here ``1>`` is the prompt. The number is counting the number of commands you
  134. have executed. Type ``help`` for a list of commands. It also has
  135. autocompletion, so you can start typing a command and then hit the
  136. ``tab`` key to show a list of possible matches.
  137. Now let's create a queue we can send messages to::
  138. 1> exchange.declare testexchange direct
  139. ok.
  140. 2> queue.declare testqueue
  141. ok. queue:testqueue messages:0 consumers:0.
  142. 3> queue.bind testqueue testexchange testkey
  143. ok.
  144. This created the direct exchange ``testexchange``, and a queue
  145. named ``testqueue``. The queue is bound to the exchange using
  146. the routing key ``testkey``.
  147. From now on all messages sent to the exchange ``testexchange`` with routing
  148. key ``testkey`` will be moved to this queue. We can send a message by
  149. using the ``basic.publish`` command::
  150. 4> basic.publish "This is a message!" testexchange testkey
  151. ok.
  152. Now that the message is sent we can retrieve it again. We use the
  153. ``basic.get`` command here, which pops a single message off the queue,
  154. this command is not recommended for production as it implies polling, any
  155. real application would declare consumers instead.
  156. Pop a message off the queue::
  157. 5> basic.get testqueue
  158. {'body': 'This is a message!',
  159. 'delivery_info': {'delivery_tag': 1,
  160. 'exchange': u'testexchange',
  161. 'message_count': 0,
  162. 'redelivered': False,
  163. 'routing_key': u'testkey'},
  164. 'properties': {}}
  165. AMQP uses acknowledgment to signify that a message has been received
  166. and processed successfully. The message is sent to the next receiver
  167. if it has not been acknowledged before the client connection is closed.
  168. Note the delivery tag listed in the structure above; Within a connection channel,
  169. every received message has a unique delivery tag,
  170. This tag is used to acknowledge the message. Note that
  171. delivery tags are not unique across connections, so in another client
  172. the delivery tag ``1`` might point to a different message than in this channel.
  173. You can acknowledge the message we received using ``basic.ack``::
  174. 6> basic.ack 1
  175. ok.
  176. To clean up after our test session we should delete the entities we created::
  177. 7> queue.delete testqueue
  178. ok. 0 messages deleted.
  179. 8> exchange.delete testexchange
  180. ok.