分列模式(Fanout)
任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有 Queue上。
1.这种模式需要提前将Exchange与Queue进行绑定,一个Exchange可以绑定多个 Queue,一个Queue可以同多个Exchange进行绑定。
2.这种模式不需要RouteKey
3.如果接受到消息的Exchange没有与任何Queue绑定,则消息会被抛弃。
步骤:
1.创建项目,pom文件导入依赖
org.springframework.amqp
spring‐rabbit
2.1.4.RELEASE
2.编写配置文件applicationContext-rabbitmq-producer.xml
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">
3.编写消息生产者代码
public class RabbitDemo2 {
public static void main(String[] args) {
//加载配置文件
ApplicationContext app = new ClassPathXmlApplicationContext("applicationContext-rabbit-producer.xml");
//获取rabbitTemplate模板
RabbitTemplate rabbitTemplate = (RabbitTemplate) app.getBean("rabbitTemplate");
//参数2代表Queues的名字,参数3代表要发送的消息
for (int i = 0; i < 50; i++) {
rabbitTemplate.convertAndSend("chenge.text","","直接模式"+i);
}
//关闭连接
((ClassPathXmlApplicationContext) app).close();
}
4.编写消息消费者代码
1.编写消息监听类
public class MessgerConsumer1 implements MessageListener {
public void onMessage(Message message) {
System.out.println("消费者1:"+new String(message.getBody()));
}
}
2.创建配置文件applicationContext-rabbitmq-consumer.xml
xmlns:rabbit="http://www.springframework.org/schema/rabbit"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans-4.2.xsd
http://www.springframework.org/schema/rabbit http://www.springframework.org/schema/rabbit/spring-rabbit.xsd">