Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)。
每一个
Queue
都与
Exchange
设置一个
BindingKey
发布者发送消息时,指定消息的
RoutingKey
Exchange
将消息路由到
BindingKey
与消息
RoutingKey
一致的队列
案例:利用SpringAMQP演示DirectExchange的使用
实现思路如下:
1.
利用
@RabbitListener
声明
Exchange
、
Queue
、
RoutingKey
2.
在
consumer
服务中,编写两个消费者方法,分别监听
direct.queue1
和
direct.queue2
3.
在
publisher
中编写测试方法,向
itcast
.
direct
发送消息
代码实现:
在consumer服务声明Exchange、Queue
1.
在
consumer
服务中,编写两个消费者方法,分别监听
direct
.queue1
和
direct
.queue2
,
2.
并利用
@RabbitListener
声明
Exchange
、
Queue
、
RoutingKey
@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("DirectQueue1消费者接收到消息:【" + 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("DirectQueue2消费者接收到消息:【" + msg + "】");
}
在publisher服务发送消息到DirectExchange
在publisher服务的SpringAmqpTest类中添加测试方法:
@Test
public void testDirectExchange(){
//交换机名称
String exchangeName = "itcast.direct";
//发送消息
String message = "hello,red";
rabbitTemplate.convertAndSend(exchangeName,"red",message);
}
小结:
Direct交换机与Fanout交换机的差异
•
Fanout
交换机将消息路由给每一个与之绑定的队列
•
Direct
交换机根据
RoutingKey
判断路由给哪个队列
•
如果多个队列具有相同的
RoutingKey
,则与
Fanout
功能类似
基于@RabbitListener注解声明队列和交换机常见注解
•
@Queue
•
@Exchange