routing.rst 17 KB

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