1.完成基本使用中的环境搭建
2.编写消息接受者
使用交换机能批量发送信息至每个符合规则的队列,完成多个队列都能收到相同消息的功能。
bindingKey相当于令牌,指这个接受者只接收具有该令牌的消息
@Component
public class SpringRabbitListener {
//@RabbitListener 单注解直接创建并绑定交换机与队列和bindingKey
@RabbitListener(bindings = @QueueBinding(
//队列名
value = @Queue(name ="testDirect.queue1"),
//交换机
exchange = @Exchange(name = "test.direct",type = ExchangeTypes.DIRECT),
//bindingKey
key = {"red","blue"}
))
public void listenDirectQueue1(String msg) {
System.out.println("what receive in testDirect.queue1 is :"+msg);
}
//@RabbitListener 单注解直接创建并绑定交换机与队列和bindingKey
@RabbitListener(bindings = @QueueBinding(
//队列名
value = @Queue(name ="testDirect.queue2"),
//交换机
exchange = @Exchange(name = "test.direct",type = ExchangeTypes.DIRECT),
//bindingKey
key = {"red","yellow"}
))
public void listenDirectQueue2(String msg) {
System.out.println("what receive in testDirect.queue2 is :"+msg);
}
}
3.编写消息发送者
routingKey指使该消息具有某个令牌,这样就能和接受者队列的bindingKey对应
@Test
public void sendMessageToExchangeDirect() {
String exchangeName = "test.direct";
String msg="hello,yellow";
String routingKey = "yellow";
rabbitTemplate.convertAndSend(exchangeName,routingKey,msg);
}