RabbitMQ06_Topic模型
上一个模型(订阅直连(Direct)模型)实现了同的消息可以被不同队列消费的需求,但是它还是不够灵活。
Topic 模型允许队列绑定 Routing key 时使用通配符,这种模型的 Routingkey 一般由一个或多个单词组成,多个单词以"."分隔,例如 item.insert
可以使用 * 号匹配一个单词,使用 # 号匹配多个单词
代码示例:
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topics", "topic");
String routingkey = "user.save.all";
channel.basicPublish("topics", routingkey, null, ("topic 动态路由模型,route key:["+routingkey+"]").getBytes());
RabbitMQUtils.closeConnectionAndChannel(channel, connection);
}
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topics", "topic");
String queue = channel.queueDeclare().getQueue();
channel.queueBind(queue, "topics", "user.*");
channel.basicConsume(queue, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
System.out.println("消费者1:"+new String(body));
}
});
}
public static void main(String[] args) throws IOException {
Connection connection = RabbitMQUtils.getConnection();
Channel channel = connection.createChannel();
channel.exchangeDeclare("topics", "topic");
String queue = channel.queueDeclare().getQueue();
channel.queueBind(queue, "topics", "user.#");
channel.basicConsume(queue, true, new DefaultConsumer(channel){
@Override
public void handleDelivery(String consumerTag, Envelope envelope, BasicProperties properties, byte[] body)
throws IOException {
System.out.println("消费者2:"+new String(body));
}
});
}
消费者1只接收到1条消息,而消费者2接收到了两条消息:
消费者1:topic 动态路由模型,route key:[user.save]
消费者2:topic 动态路由模型,route key:[user.save]
消费者2:topic 动态路由模型,route key:[user.save.aaa]
版权说明 : 本文为转载文章, 版权归原作者所有 版权申明
原文链接 : https://blucoding.blog.csdn.net/article/details/109538481
内容来源于网络,如有侵权,请联系作者删除!