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條消息