rabbitMQ Publish/Subscribe

目录

1、Exchange(交换机)

2、Temporary queues

3、Bindings

4、Direct exchange

5、Topic exchange


1、Exchange(交换机)

        The core idea in the messaging model in RabbitMQ is that the producer never sends any messages directly to a queue. Actually, quite often the producer doesn't even know if a message will be delivered to any queue at all.

        Instead, the producer can only send messages to an exchange. An exchange is a very simple thing. On one side it receives messages from producers and the other side it pushes them to queues. The exchange must know exactly what to do with a message it receives. Should it be appended to a particular queue? Should it be appended to many queues? Or should it get discarded. The rules for that are defined by the exchange type.

2、Temporary queues

        Firstly, whenever we connect to Rabbit we need a fresh, empty queue. To do it we could create a queue with a random name, or, even better - let the server choose a random queue name for us.

        once the consumer connection is closed, the queue should be deleted. 

String queueName = channel.queueDeclare().getQueue();

3、Bindings

        We've already created a fanout exchange and a queue. Now we need to tell the exchange to send messages to our queue. That relationship between exchange and a queue is called a binding.

channel.queueBind(queueName, "logs", "");
4、Direct exchange

Direct exchange 类似于kafka中的Topic

在上图中,可以理解为有三个topic分别为 orange、black、green,消费者1消费orange,消费者2消费black和green 

5、Topic exchange

        The binding key must also be in the same form. The logic behind the topic exchange is similar to a direct one - a message sent with a particular routing key will be delivered to all the queues that are bound with a matching binding key. However there are two important special cases for binding keys:

  • * (star) can substitute for exactly one word.(一个精确的单词)
  • # (hash) can substitute for zero or more words.(零或者很多单词)

Messages sent to a topic exchange can't have an arbitrary routing_key - it must be a list of words, delimited by dots(一组单词,由"."分隔)

消息的选择性接收是通过绑定键匹配来决定的

  • 生产者绑定键

quick.orange.rabbit
lazy.orange.elephant
quick.orange.fox
lazy.brown.fox
lazy.pink.rabbit
quick.brown.fox
quick.orange.new.rabbit
lazy.orange.new.rabbit

  • 消费者绑定键

Consumer1: *.orange.*

Consumer2: *.*.rabbit or lazy.#

  • 预期结果

C1C2

C1C2

C1

C2

C2

discarded 不匹配会丢弃

LOST 违反匹配规则会丢失

C2

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值