DirectExchange:
路由模式模型
代码实现
直接通过注解方式绑定交换机和队列,这里边加了key也就是BingdingKey绑定key,可以看作交换机的路由规则,交换机收到消息后读取消息中指定的Routingkey发送到存有相应BingdingKey的队列中。
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(name = "direct.queue1"),
exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT),
key = {"red","blue"}
)
)
public void listenDirectQueue1(String msg){
System.out.println("从queue1中获取到了消息:"+msg);
}
@RabbitListener(
bindings = @QueueBinding(
value = @Queue(name = "direct.queue2"),
exchange = @Exchange(name = "itcast.direct",type = ExchangeTypes.DIRECT),
key = {"red","yellow"}
)
)
public void listenDirectQueue2(String msg){
System.out.println("从queue2中获取到了消息:"+msg);
}
然后编写publisher消费者的代码:
@Test
public void testDirectExchangeSend() {
//发送消息
String DirectChangeName = "itcast.direct";//交换机的名字
String msg = "我是direct交换机发送的消息";
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend(DirectChangeName, "red", msg+i);
}
for (int i = 0; i < 10; i++) {
rabbitTemplate.convertAndSend(DirectChangeName, "yellow", msg+i);
}
}
两个队列的BingingKey中都有red 所以两个都接收到了
当RoutingKey是yellow时候只有一个接收到了 因为只有那一个交换机里BingingKey里有yellow
能看到控制台接收并打印的消息
也可以看到队列
总结: