美文网首页消息队列
RabbitMQ消息队列---Topic Exchange细节总

RabbitMQ消息队列---Topic Exchange细节总

作者: ___TheOne___ | 来源:发表于2018-05-03 11:08 被阅读47次

RabbitMQ主题交换机(Topic Exchange)细节学习,英文官方文档

主题交换机(Topic Exchange)

    发送到主题交换机(Topic Exchange)的消息,不能随意设置其路由键(routing key):路由键需要是一个单词列表,单词之间使用点分隔符分隔。eg:lazy.brown.fox  这个路由键单词建议根据消息队列功能特点来设置。且路由键可设置最大值为255个字节。

    主体交换机和消息队列之间的绑定键(binding key),需要和上述的路由键(routing key)格式一致。同时这个绑定键有两个特殊字符可以使用:
* (星号) :可以代替指定位置的一个单词
# (井号) :可以代替指定位置的一个单词或多个单词。

当了解了上面的知识,下面的实例将非常容易理解:

主题交换机和队列之间,绑定键设置
    在这个实例中,我们将会发送关于动物的相关消息。同时这些消息的路由键,将会包含3个单词(2个点分隔符)。路由键第一个单词将会描述动物速度(speed),第二个单词描述动物颜色,第三个单词描述动物种类。路由键格式为:"<speed>.<colour>.<species>"

We created three bindings: Q1 is bound with binding key ".orange." and Q2 with "..rabbit" and "lazy.#".

These bindings can be summarised as:

  • Q1 is interested in all the orange animals.
  • Q2 wants to hear everything about rabbits, and everything about lazy animals.

A message with a routing key set to "quick.orange.rabbit" will be delivered to both queues. Message "lazy.orange.elephant" also will go to both of them. On the other hand "quick.orange.fox" will only go to the first queue, and "lazy.brown.fox" only to the second. "lazy.pink.rabbit" will be delivered to the second queue only once, even though it matches two bindings. "quick.brown.fox" doesn't match any binding so it will be discarded.

What happens if we break our contract and send a message with one or four words, like "orange" or "quick.orange.male.rabbit"? Well, these messages won't match any bindings and will be lost.

On the other hand "lazy.orange.male.rabbit", even though it has four words, will match the last binding and will be delivered to the second queue.

Topic exchange

Topic exchange is powerful and can behave like other exchanges.

When a queue is bound with "#" (hash) binding key - it will receive all the messages, regardless of the routing key - like in fanout exchange.

When special characters "*" (star) and "#" (hash) aren't used in bindings, the topic exchange will behave just like a direct one.

实例代码见于:spring-boot-rabbitmq对应目录是jadenTopic

相关文章

网友评论

    本文标题:RabbitMQ消息队列---Topic Exchange细节总

    本文链接:https://www.haomeiwen.com/subject/pjjkrftx.html