Fanout Exchange 不需要路由键。只需要简单的将队列绑定到交换机上。一个发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。很像子网广播,每台子网内的主机都获得了一份复制的消息。Fanout交换机转发消息是最快的(不需要做路由规则的判断)。
任何发送到Fanout Exchange的消息都会被转发到与该Exchange绑定(Binding)的所有Queue上。
编码实践
一、生产者和消费者模型
1、创建连接(生产端)
Connection connection = null;
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("youHost");
connectionFactory.setUsername("userName");
connectionFactory.setPassword("password");
connection = connectionFactory.newConnection();
2、创建channel(生产端)
Channel channel = connection.createChannel();
3、创建exchange(生产端)
channel.exchangeDeclare("myExchange", "fanout", true, false, null);
4、创建queue(生产端)
channel.queueDeclare("testQueue",true,false,false,null);
channel.queueDeclare("testQueue1",true,false,false,null);
channel.queueDeclare("testQueue2",true,false,false,null);
5、绑定路由键(生产端)
//三个不同的队列,三个不同的路由键
channel.queueBind("testQueue","myExchange","test");
channel.queueBind("testQueue1","myExchange","test1");
channel.queueBind("testQueue2","myExchange","test2");
6、发送消息(生产端)
//发送消息,路由键为myExchange
for(int i=0;i<10;i++){
channel.basicPublish("myExchange","myExchange",null,(msg + i).getBytes());
}
发送消息结果:
上述结果表明:fanout类型的交换机,不处理路由键,当发送消息时,都会发送消息到绑定了该交换机的消息队列中
1、创建连接(消费者端)
Connection connection = null;
ConnectionFactory connectionFactory = new ConnectionFactory();
connectionFactory.setHost("you host");
connectionFactory.setUsername("xxxx");
connectionFactory.setPassword("xxxx");
connection = connectionFactory.newConnection();
2、创建channel(消费者端)
Channel channel = connection.createChannel();
3、创建消费者(消费者端)
QueueingConsumer consumer = new QueueingConsumer(channel);
4、监听消息队列(消费者端)
channel.basicConsume("队列名称", consumer);
5、消费消息(消费者端)
while (( delivery = consumer.nextDelivery()) != null){
byte[] body = delivery.getBody();
String msg = new String(body);
System.out.println(msg);
}