1. 程式人生 > >RabbitMQ各種交換機型別Exchange Types介紹

RabbitMQ各種交換機型別Exchange Types介紹

最新版本的RabbitMQ有四種交換機型別,分別是Direct exchange、Fanout exchange、Topic exchange、Headers exchange。

Direct Exchange – 處理路由鍵。需要將一個佇列繫結到交換機上,要求該訊息與一個特定的路由鍵完全匹配。這是一個完整的匹配。如果一個佇列繫結到該交換機上要求路由鍵 “dog”,則只有被標記為“dog”的訊息才被轉發,不會轉發dog.puppy,也不會轉發dog.guard,只會轉發dog。 


Fanout Exchange – 不處理路由鍵。你只需要簡單的將佇列繫結到交換機上。一個傳送到交換機的訊息都會被轉發到與該交換機繫結的所有佇列上。很像子網廣播,每臺子網內的主機都獲得了一份複製的訊息。Fanout交換機轉發訊息是最快的。 




Topic Exchange – 將路由鍵和某模式進行匹配。此時佇列需要繫結要一個模式上。符號“#”匹配一個或多個詞,符號“*”匹配不多不少一個詞。因此“audit.#”能夠匹配到“audit.irs.corporate”,但是“audit.*” 只會匹配到“audit.irs”。我在RedHat的朋友做了一張不錯的圖,來表明topic交換機是如何工作的: 


注:這種情況下佇列會收到所有路由器中符合topic規則的訊息

Headers exchange – 還沒有仔細研究過,複製點官方的介紹吧。

A headers exchange is designed to for routing on multiple attributes that are more easily expressed as message headers than a routing key. Headers exchanges ignore the routing key attribute. Instead, the attributes used for routing are taken from the headers attribute. A message is considered matching if the value of the header equals the value specified upon binding.

It is possible to bind a queue to a headers exchange using more than one header for matching. In this case, the broker needs one more piece of information from the application developer, namely, should it consider messages with any of the headers matching, or all of them? This is what the "x-match" binding argument is for. When the "x-match" argument is set to "any", just one matching header value is sufficient. Alternatively, setting "x-match" to "all" mandates that all the values must match.

Headers exchanges can be looked upon as "direct exchanges on steroids". Because they route based on header values, they can be used as direct exchanges where the routing key does not have to be a string; it could be an integer or a hash (dictionary) for example.


其實除了上面四種以外還有一種Default Exchange,它是一種特別的Direct Exchange。

當你手動建立一個佇列時,後臺會自動將這個佇列繫結到一個名稱為空的Direct型別交換機上,繫結路由名稱與佇列名稱相同。有了這個預設的交換機和繫結,我們就可以像其他輕量級的佇列,如Redis那樣,直接操作佇列來處理訊息。不過只是看起來是,實際上在RabbitMQ裡直接操作是不可能的。訊息始終都是先發送到交換機,由交換級經過路由傳送給佇列,消費者再從佇列中獲取訊息的。不過由於這個預設交換機和路由的關係,使我們只關心佇列這一層即可,這個比較適合做一些簡單的應用,畢竟沒有發揮RabbitMQ的最大功能,如果都用這種方式去使用的話就真是殺雞用宰牛刀了。

參考: