RabbitMQ06_Topic模型

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);
}
  • 消息消费者1:
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));
        }
    });
}
  • 消息消费者2:
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));
        }
    });
}
  • 测试分别发送 Routing key 基于 user.save 和 user.save.aaa 的两条消息,结果:

消费者1只接收到1条消息,而消费者2接收到了两条消息:

消费者1:topic 动态路由模型,route key:[user.save]
消费者2:topic 动态路由模型,route key:[user.save]
消费者2:topic 动态路由模型,route key:[user.save.aaa]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值