routing.rst 8.1 KB

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