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符合通配符表达式即可。
通配符:#表示一个或多个字符。*表示一个字符

评论 6
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值