1. 程式人生 > >RabbitMQ訊息佇列(二) fanout 廣播模式

RabbitMQ訊息佇列(二) fanout 廣播模式

先粘程式碼

生產者

                ConnectionFactory connectionFactory = new ConnectionFactory();

                Connection connection = connectionFactory.newConnection();

                Channel channel = connection.createChannel();


                channel.exchangeDeclare(EXCHANGE_NAME,BuiltinExchangeType.FANOUT);

                channel.basicPublish(EXCHANGE_NAME,"",null,"你是不是傻".getBytes());

                channel.close();

                connection.close();


消費者


class Consume{

    static Channel channel;
    private final static String QUEUE_NAME = "test_queue_fanout_1";

    private final static String EXCHANGE_NAME = "fanout";

    public static void main(String[] args) {
        try {
            ConnectionFactory connectionFactory = new ConnectionFactory();

            Connection connection = connectionFactory.newConnection();


            channel = connection.createChannel();

            channel.exchangeDeclare(EXCHANGE_NAME, BuiltinExchangeType.FANOUT);

            String queueName = channel.queueDeclare().getQueue();

            System.out.println(queueName);
            System.out.println(QUEUE_NAME);
          

          channel.queueBind(queueName,EXCHANGE_NAME,"");


            Consumer consumer = new DefaultConsumer (channel){


                @Override
                public void handleDelivery(String consumerTag, Envelope envelope, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    super.handleDelivery(consumerTag, envelope, properties, body);
                    System.out.println(new String(body,"utf-8"));




                }
            };


            channel.basicConsume(queueName,true,consumer);
            // 監聽佇列,手動返回完成


        } catch (IOException e) {
            e.printStackTrace();
        } catch (TimeoutException e) {
            e.printStackTrace();
        }

    }


}


7925105-628b5cff291bf824.png image.png

注意channel.queueBind(queueName,EXCHANGE_NAME,""); 這裡的queueName 不是之前定義的那個

上圖顯示 多開了幾個消費者 結果每一個消費者的queueName都不一樣