Direct Exchange 会将接收到的消息根据规则路由到指定的Queue,因此称为路由模式(routes)。
- 每一个Queue都与Exchange设置一个BindingKey
- 发布者发送消息时,指定消息的RoutingKey
- Exchange将消息路由到BindingKey与消息RoutingKey一致的队列
实现思路如下:
- 在consumer服务中,编写两个消费者方法,分别监听direct.queue1和direct.queue2
- 利用@RabbitListener声明Exchange、Queue、BindingKey
- 在publisher中编写测试方法
- 向指定Exchange和RoutingKey(RoutingKey就是BindingKey)发送消息
在consumer服务中,编写两个消费者方法
@RabbitListener(bindings = @QueueBinding( value = @Queue("direct.queue1"), exchange = @Exchange("marw.direct"), key={"red","blue"} )) public void listenDirectQueue1(String msg) throws InterruptedException { System.out.println("listenDirectQueue1 消费者接收到消息 :【" + msg + "】"); } @RabbitListener(bindings = @QueueBinding( value = @Queue("direct.queue2"), exchange = @Exchange("marw.direct"), key={"red","yellow"} )) public void listenDirectQueue2(String msg) throws InterruptedException { System.err.println("listenDirectQueue2 消费者接收到消息 :【" + msg + "】"); }
在publisher中编写测试方法
@Test public void testDirectQueue() throws InterruptedException { String queueName = "marw.direct"; String message = "hello, Direct queue message"; rabbitTemplate.convertAndSend(queueName, "red", message); }