When to use direct exchange over fanout exchange

后端 未结 3 973
醉话见心
醉话见心 2021-02-13 08:43

As far as I can tell, there is no proper use case for a direct exchange, as anything you can do with it you can do with a fanout exchange, only more expandably.

More spec

3条回答
  •  小鲜肉
    小鲜肉 (楼主)
    2021-02-13 09:48

    Compared to the fanout exchange, the direct exchange allows some filtering based on the message's routing key to determine which queue(s) receive(s) the message. With a fanout exchange, there is no such filtering and all messages go to all bound queues.

    So if you have a direct exchange with several queues bound with the same routing key, and all messages have this key, then you have the same behavior as the fanout exchange. This is better explained in tutorial 4 on the RabbitMQ website.

    In the image upload use case, you can use:

    • a fanout exchange with two queues (one for the thumbnail worker, one for the score computation worker). The routing key is ignored.

      fanout-exchange
      |--> queue --> thumbnail-worker
      `--> queue --> score-worker
      
    • a direct exchange with again two queues. Queues are bound with the image-processing key for instance, and messages with this key will be queued to both queues.

      direct-exchange
      |--["image-processing"]--> queue --> thumbnail-worker
      `--["image-processing"]--> queue --> score-worker
      

      Of course, in this situation, if the message's routing key doesn't match the binding key, none of the queues will receive the message.

    You can't put the two workers on the same queue, because messages will be load balanced between them: one worker will see half of the messages.

提交回复
热议问题