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