基于注解声明队列和交换机

发布时间 2023-09-13 00:19:42作者: liyongliang的博客

一,生产两个消费监听者(消费端)

 

@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("消费者接收到direct.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("消费者接收到direct.queue2的消息:【" + msg + "】");
}

消息发送,需要指名交换机名称,路由器名称,还有发送的内容(发送端)

@Test
public void testSendDirectExchange() {
// 交换机名称
String exchangeName = "itcast.direct";
// 消息
String message = "hello Mq!";
// 发送消息
rabbitTemplate.convertAndSend(exchangeName, "red", message);
}