zoukankan      html  css  js  c++  java
  • springboot整合rabbitmq(topic主题模式)

    在direct模式基础上改,但是此次使用注解方式

    消费者

    修改对应的consumer,用注解方式定义交换机和队列的关系

    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "duanxin.topic.queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
            key = "#.duanxin.#"
    ))
    public class TopicDuanxinConsumer {
    
        @RabbitHandler
        public void receiveMsg(String msg){
            System.out.println("TopicDuanxinConsumer ---接收到的订单信息是:->" + msg);
        }
    }
    
    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "email.topic.queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
            key = "*.email.#"
    ))
    public class TopicEmailConsumer {
    
        @RabbitHandler
        public void receiveMsg(String msg){
            System.out.println("TopicEmailConsumer ---接收到的订单信息是:->" + msg);
        }
    }
    
    @Service
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(value = "sms.topic.queue",durable = "true",autoDelete = "false"),
            exchange = @Exchange(value = "topic_order_exchange",type = ExchangeTypes.TOPIC),
            key = "com.#"
    ))
    public class TopicSmsConsumer {
    
        @RabbitHandler
        public void receiveMsg(String msg){
            System.out.println("TopicSmsConsumer ---接收到的订单信息是:->" + msg);
        }
    }
    
    • 启动SpringbootOrderRabbitmqConsumerApplication,查看交换机队列是否绑定成功
      image
      image
      image

    生产者

    只需要定义路由规则即可#是任意个,可以有多个,可以有一个,也可以没有;*最少有一个

        public void makeOrderTopic(String userId,String productId,int num){
    
            String orderId = UUID.randomUUID().toString();
            System.out.println("订单生成成功:" + orderId);
    
            String exchangeName = "topic_order_exchange";
            String routingKey = "com.duanxin";
            //@param1 交换机 @param2 路由key/queue队列名称 @param3 消息内容
            rabbitTemplate.convertAndSend(exchangeName,routingKey,orderId);
        }
    
    • 运行测试类
    @Test
    void contextLoads2() {
       orderService.makeOrderTopic("1","1",12);
    }
    

    image
    同时客户端也可以收到,当然再次发送也可以收到。
    image

    针对于注解方式

    虽然简洁,但是还是推荐配置类方式,毕竟各有多爱,另外配置类推荐写在客户端。

  • 相关阅读:
    RHEL7挂载ISO做本地yum
    服务器虚拟化架构突出优势
    国内公共DNS
    世界上最小的发行版之一Tiny Core
    VMware v12.1.1 专业版以及永久密钥
    Webbench网站压力测试
    Web.xml配置详解之context-param
    SpringMvc自动代理
    SpringMvc aop before
    SpringMvc 面向切面1
  • 原文地址:https://www.cnblogs.com/kaka-qiqi/p/14881816.html
Copyright © 2011-2022 走看看