1. 程式人生 > >訊息中介軟體--RabbitMQ學習(六)

訊息中介軟體--RabbitMQ學習(六)

Fanout Exchange學習

Fanout Exchange介紹

  1. 不處理路由鍵,只需要簡單的將佇列繫結到交換機上
  2. 傳送到交換機的訊息都會被轉發到與該交換機繫結的所有佇列上
  3. 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();
}

}