上一篇:springboot整合rabbitMQ模拟简单收发消息
https://blog.csdn.net/m0_67930426/article/details/134904766
本篇代码基于上一篇继续写
目录
Fanout 交换机
1. add queue
2. add Exchange
3.绑定队列
Direct 交换机
1. add queue
2. add Exchange
3.绑定队列,并设置Routing key
Topic 交换机
1.add queue
2.add Exchange
3.绑定队列
Fanout 交换机
fanout exchange 会将接收到的消息广播到每一个跟其绑定的queue
1. add queue
2. add Exchange
3.绑定队列
消费者监听队列
@RabbitListener(queues = "fanout.queue1")public void eee(String msg){System.out.println("消费者e收到了fanout.queue1的消息:【"+msg+"】");}@RabbitListener(queues = "fanout.queue2")public void fff(String msg){System.err.println("消费者f收到了fanout.queue2的消息:【"+msg+"】");}
单元测试模拟业务发送消息
@Testvoid Test3Send(){String ExchangeName = "aaa.fanout";String msg = "rabbitMQ<消息队列>";rabbitTemplate.convertAndSend(ExchangeName,null, msg);}
Direct 交换机
Direct Exchange 会将接收的消息根据规则路由到指定的queue
1. add queue
2. add Exchange
3.绑定队列,并设置Routing key
消费者监听队列
@RabbitListener(queues = "direct.queue1")public void ggg(String msg){System.out.println("消费者g收到了fanout.queue1的消息:【"+msg+"】");}@RabbitListener(queues = "direct.queue2")public void hhh(String msg){System.err.println("消费者h收到了fanout.queue2的消息:【"+msg+"】");}
单元测试模拟业务发送消息
@Testvoid Test3Send() {String ExchangeName = "bbb.direct";String msg = "rabbitMQ<消息队列>";rabbitTemplate.convertAndSend(ExchangeName,"red" , msg);}
Routing key: " red "
预期结果是,两个消费者都收到了消息
将Routing key 的值改为blue
预期结果,只有消费者g接收到了消息
Topic 交换机
1.add queue
2.add Exchange
3.绑定队列
消费者监听队列
@RabbitListener(queues = "topic.queue1")public void jjj(String msg){System.out.println("消费者j收到了fanout.queue1的消息:【"+msg+"】");}@RabbitListener(queues = "topic.queue2")public void kkk(String msg){System.err.println("消费者k收到了fanout.queue2的消息:【"+msg+"】");}
单元测试模拟业务发送消息
@Testvoid Test3Send() {String ExchangeName = "ccc.topic";String msg = "rabbitMQ";rabbitTemplate.convertAndSend(ExchangeName,"zhejiang.new" , msg);}
Routing key : " zhejiang.new "
预期结果是k收到消息
Routing key: " china.new "
预期结果,两个消费者都接收到了消息