15-SpringAMQP-TopicExchange

本文介绍了SpringAMQP中的TopicExchange,它类似于DirectExchange,但routingKey支持使用通配符,如#和*。通过案例展示了如何配置Exchange、Queue,并在consumer服务中创建两个监听topic.queue1和topic.queue2的消费者方法。在publisher服务中,测试向itcast.topic发送消息。总结了Direct和Topic交换机的区别,强调Topic交换机在routingKey的灵活性和通配符的使用。
摘要由CSDN通过智能技术生成

15-SpringAMQP-TopicExchange

1.发布订阅-TopicExchange

TopicExchange与DirectExchange类似,区别在于routingKey必须是多个单词的列表,并且以 . 分割。

Queue与Exchange指定BindingKey时可以使用通配符:

​ #:代指0个或多个单词

​ *:代指一个单词

china.news 代表有中国的新闻消息;

china.weather 代表中国的天气消息;

japan.news 则代表日本新闻

japan.weather 代表日本的天气消息;

在这里插入图片描述

1.案例:利用SpringAMQP演示TopicExchange的使用

实现思路如下:

​ 并利用@RabbitListener声明Exchange、Queue、RoutingKey

​ 在consumer服务中,编写两个消费者方法,分别监听topic.queue1和topic.queue2

​ 在publisher中编写测试方法,向itcast. topic发送消息

步骤1:在consumer服务声明Exchange、Queue

在consumer服务中,编写两个消费者方法,分别监听topic.queue1和topic.queue2,并利用@RabbitListener声明Exchange、Queue、RoutingKey

@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "topic.queue1"),
    exchange = @Exchange(name = "itcast.topic", type = ExchangeTypes.TOPIC),
    key = "china.#"))
    public void listenTopicQueue1(String msg){
        System.out.println("消费者1接收到Topic消息:【"+msg+"】");
    }
    
@RabbitListener(bindings = @QueueBinding(
    value = @Queue(name = "topic.queue2"),
    exchange = @Exchange(name = "itcast.topic", type = ExchangeTypes.TOPIC),
    key = "#.news"))
    public void listenTopicQueue2(String msg){
        System.out.println("消费者2接收到Topic消息:【"+msg+"】");
    }

步骤2:在publisher服务发送消息到TopicExchange

​ 在publisher服务的SpringAmqpTest类中添加测试方法:

@Test
public void testTopicExchange() {
    // 队列名称
    String exchangeName = "itcast.topic";
    // 消息
    String message = "喜报!孙悟空大战哥斯拉,胜!";
    // 发送消息
    rabbitTemplate.convertAndSend(exchangeName, "china.news", message);
}

3.总结:

描述下Direct交换机与Topic交换机的差异?

​ Topic交换机接收的消息RoutingKey必须是多个单词,以 . 分割

​ Topic交换机与队列绑定时的bindingKey可以指定通配符

​ #:代表0个或多个词

​ *:代表1个词

在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值