RabbitMQ:Fanout Exchange
一.Fanout Exchange相关介绍
不处理路由键,只需要将简单的将队列绑定到交换机上。
发送到交换机的消息都会被转发到与该交换机绑定的所有队列上。
Fanout交换机转发消息是最快的。
二.消费者
public static void main(String[] args) throws IOException, TimeoutException, InterruptedException { //创建一个连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.10.132"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); //创建连接 Connection connection = connectionFactory.newConnection(); //通过连接创建一个Channel Channel channel = connection.createChannel(); //创建一个队列 String exchangeName = "test_fanout_exchange"; String exchangeType = "fanout"; String queueName1 = "fanout1"; String queueName2 = "fanout2"; String routingKey = ""; //声明一个交换机 channel.exchangeDeclare(exchangeName,exchangeType,true,false,false,null); //声明队列 channel.queueDeclare(queueName1,false,false,false,null); channel.queueDeclare(queueName2,false,false,false,null); //建立交换机、队列的绑定关系 channel.queueBind(queueName1,exchangeName,routingKey); channel.queueBind(queueName2,exchangeName,routingKey); //创建一个消费者 QueueingConsumer consumer = new QueueingConsumer(channel); //设置Channel channel.basicConsume(queueName1,true,consumer); channel.basicConsume(queueName2,true,consumer); //获取消息 while (true){ QueueingConsumer.Delivery delivery = consumer.nextDelivery(); String msg = new String(delivery.getBody()); System.out.println("消费端:"+msg); } }
三.生产者
public static void main(String[] args) throws IOException, TimeoutException { //创建一个连接工厂 ConnectionFactory connectionFactory = new ConnectionFactory(); connectionFactory.setHost("192.168.10.132"); connectionFactory.setPort(5672); connectionFactory.setVirtualHost("/"); //创建连接 Connection connection = connectionFactory.newConnection(); //通过连接创建一个Channel Channel channel = connection.createChannel(); //通过Channel发送数据 channel.basicPublish("test_fanout_exchange","",null,"test fanout exchange".getBytes()); channel.basicPublish("test_fanout_exchange","",null,"test fanout exchange".getBytes()); //关闭连接 channel.close(); connection.close(); }
关系拓扑:
运行结果: