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);
}
本文介绍如何使用RabbitMQ实现消息的发布与订阅模式。通过配置不同的交换机、队列及绑定键(bindingKey),实现了消息的精确投递。具体演示了如何设置两个队列(testDirect.queue1, testDirect.queue2)来接收特定类型的消息,并通过消息发送者的路由键(routingKey)确保消息能够准确地被目标队列接收到。
2386

被折叠的 条评论
为什么被折叠?



