分列模式(Fanout):
当我们需要将消息一次发给多个队列时,需要使用这种模式
1:简述:
任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有 Queue上。
1.可以理解为路由表的模式
2.这种模式不需要RouteKey
3.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个 Queue,一个Queue可以同多个Exchange进行绑定。多对多的关系。
4.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。
2:交换器绑定队列
(1):新增队列 test1 和 test2
(2):新增交换器 wchExchange
(3):将队列和交换器绑定
点击 wchExchange 进入交换器管理界面,操作后如下图:
3:代码实现:
代码参考:https://gitee.com/WChengHe/RabbitmqDemo
代码中pom文件、配置文件及启动类参考上一篇:https://blog.csdn.net/qq_22596931/article/details/89329024
测试类FanoutTest.java:
package com.wch.demo.fanout;
import com.wch.demo.DemoApplication;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest(classes = DemoApplication.class)
public class FanoutTest {
@Autowired
private RabbitTemplate rabbitTemplate;
@Test
public void testSendFanout(){
rabbitTemplate.convertAndSend("wchExchange","","测试分列模式");
}
}
在编写完测试类后,我们可以运行一下这个类,然后在界面:http://192.168.225.100:15672/#/queues,可以查看到我们交换器绑定的两个队列都保存有一条消息,说明是正常的。
在上述内容之后我们可以开始编写消费者:
消费者Customer2.java
package com.wch.demo.fanout;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "test1")
public class Customer2 {
@RabbitHandler
public void showMessage(String message){
System.out.println("test1接收到消息:"+message);
}
}
消费者Customer3.java
package com.wch.demo.fanout;
import org.springframework.amqp.rabbit.annotation.RabbitHandler;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;
@Component
@RabbitListener(queues = "test2")
public class Customer3 {
@RabbitHandler
public void showMessage(String message){
System.out.println("test2接收到消息:"+message);
}
}
完成上述代码编写后进行测试,运行后查看控制台:
在控制台中我们可以看到,生成的消息被消费者消费了。