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的最大功能,如果都用這種方式去使用的話就真是殺雞用宰牛刀了。

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章