1. 程式人生 > 其它 >RabbitMQ學習交換機之topic模型

RabbitMQ學習交換機之topic模型

在這裡插入圖片描述
direct型交換機與佇列繫結時可以配置多個rzaioutingKey,這樣為同一個佇列配置多個routingKey難免會麻煩。所以topic型別交換機由此誕生。在交換機與佇列繫結時配置routingKey時通過萬用字元的方式進行設定,在傳送訊息時的routingKey只要能滿足萬用字元表示式即可

生產者

Channel channel = connection.createChannel();
        //宣告topic型別交換機
        channel.exchangeDeclare("publish_subscribe_topic_exchange", BuiltinExchangeType.
TOPIC,true,false,false,null); channel.queueDeclare("publish_subscribe_topic_queue1",true,false,false,null); channel.queueDeclare("publish_subscribe_topic_queue2",true,false,false,null); //交換機與佇列繫結 channel.queueBind("publish_subscribe_topic_queue1"
,"publish_subscribe_topic_exchange","#.red"); channel.queueBind("publish_subscribe_topic_queue1","publish_subscribe_topic_exchange","green.*"); channel.queueBind("publish_subscribe_topic_queue2","publish_subscribe_topic_exchange"
,"#.blue"); String body1="這是一條red結尾訊息"; channel.basicPublish("publish_subscribe_topic_exchange","com.tao.red",null,body1.getBytes()); String body="這是一條green開頭包含兩個單詞的訊息"; channel.basicPublish("publish_subscribe_topic_exchange","green.msg",null,body.getBytes()); String body2="這是一條blue結尾訊息"; //指定的routingKey滿足繫結時的routingKey萬用字元表示式即可 channel.basicPublish("publish_subscribe_topic_exchange","com.tao.blue",null,body2.getBytes()); channel.close(); connection.close();

萬用字元:#表示一個或多個字元。*表示一個字元
消費者程式碼
通過佇列名進行監聽

 Channel channel = connection.createChannel();
        DefaultConsumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body) throws IOException {
                System.out.println("publish_subscribe_topic_queue1收到訊息————》"+new String(body));
            }
        };
        channel.basicConsume("publish_subscribe_topic_queue1",true,consumer);

與spring進行整合
生產者,通過萬用字元指定交換機與佇列繫結時的routingKey

 <!---->
    <rabbit:queue id="spring_topic_queue1" name="spring_topic_queue1" auto-declare="true"/>
    <rabbit:queue id="spring_topic_queue2" name="spring_topic_queue2" auto-declare="true"/>

    <!--交換機與佇列繫結-->
    <rabbit:topic-exchange name="spring_topic_exchange" auto-declare="true" id="spring_topic_exchange">
        <rabbit:bindings>
            <rabbit:binding pattern="#.red" queue="spring_topic_queue1"/>
            <rabbit:binding pattern="#.blue" queue="spring_topic_queue2"/>
        </rabbit:bindings>
    </rabbit:topic-exchange>

消費者程式碼就不在此贅述

總結
在topic型別交換機與佇列進行繫結時,通過萬用字元的方式進行配置routingKey,在傳送訊息到交換機時,只要指定的routingKey符合萬用字元表示式即可。
萬用字元:#表示一個或多個字元。*表示一個字元