消息中间件--RabbitMQ学习(六)
Fanout Exchange学习
Fanout Exchange介绍
- 不处理路由键,只需要简单的将队列绑定到交换机上
- 发送到交换机的消息都会被转发到与该交换机绑定的所有队列上
- Fanout交换机转发消息是最快的
只要交换机跟队列有绑定,就能够发送消息过去。
消费端
public class CunsumerForFanout {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("192.168.0.159");
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
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);
QueueingConsumer consumer = new QueueingConsumer(channel);
channel.basicConsume(queueName,true,consumer);
while (true){
QueueingConsumer.Delivery delivery = consumer.nextDelivery();
String msg = new String(delivery.getBody());
System.out.println("收到消息:" + msg);
}
}
}
生产端
public class ProducterForFanout {
public static void main(String[] args) throws Exception{
//1 创建一个connectionFactory
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost(“192.168.0.159”);
connectionFactory.setPort(5672);
connectionFactory.setVirtualHost("/");
//2通过连接工场创建连接
Connection connection = connectionFactory.newConnection();
//3通过connection创建channel
Channel channel = connection.createChannel();
String exchangeName = "test_fanout_exchange";
String routingKey1 = "sasa";
String msg = "hello";
for(int i=0;i<4;i++){
channel.basicPublish(exchangeName,routingKey1,null,msg.getBytes());
}
channel.close();
connection.close();
}
}