demo的前置条件和1.5-RabbitMQ-速入门demo 一样。
Fanout Exchange的基本概念:
1.1 生产者代码
package com.star.movie.exchange.fanout;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.QueueingConsumer;
import com.rabbitmq.client.QueueingConsumer.Delivery;
import com.star.movie.common.Constant;
/**
* @Description:Consumer4FanoutExchange
* @author:kaili
* @Date: 2019-04-21 22:49
**/
public class ConsumerFanoutExchange {
public static void main(String[] args) throws Exception {
//2 创建Connection
Connection connection = Constant.getConnection();
Channel channel = connection.createChannel();
//4 声明
String exchangeName = "test_fanout_exchange";
String exchangeType = "fanout";
String queueName = "test_fanout_queue";
//不设置路由键
String routingKey = "";
channel.exchangeDeclare(exchangeName, exchangeType, true, false, false, null);
channel.queueDeclare(queueName, false, false, false, null);
channel.queueBind(queueName, exchangeName, routingKey);
//durable 是否持久化消息
QueueingConsumer consumer = new QueueingConsumer(channel);
//参数:队列名称、是否自动ACK、Consumer
channel.basicConsume(queueName, true, consumer);
//循环获取消息
while(true){
//获取消息,如果没有消息,这一步将会一直阻塞
Delivery delivery = consumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("收到消息:" + msg);
}
}
}
1.2 消费者代码
package com.star.movie.exchange.fanout;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.star.movie.common.Constant;
/**
* @Description:Producer4FanoutExchange
* @author:kaili
* @Date: 2019-04-21 22:48
**/
public class ProducerFanoutExchange {
public static void main(String[] args) throws Exception {
//2 创建Connection
Connection connection = Constant.getConnection();
//3 创建Channel
Channel channel = connection.createChannel();
//4 声明
String exchangeName = "test_fanout_exchange";
//5 发送
for(int i = 0; i < 10; i ++) {
String msg = "Hello World RabbitMQ 4 FANOUT Exchange Message ...";
channel.basicPublish(exchangeName, "", null , msg.getBytes());
}
channel.close();
connection.close();
}
}
1.3.1 启动消费者代码
test_fanout_exchange交换机和队列test_fanout_queue直接绑定没有帮i的那个健
1.3.2 关闭消费者代码,启动生产者代码
生产者投递的10条消息全部投递到test_fanout_queue队列上了
1.3.3 启动消费者代码
消费了10条消息