用RabbitMq的5种交换机类型实现发送和接收消息

12 篇文章 0 订阅
11 篇文章 0 订阅

1.引言

rabbitMq的几种交换机类型在AMQP协议中均有定义,一些概念可以参考AMQP协议(https://blog.csdn.net/qq_43216019/article/details/128887061)。通过代码自己实现一遍几种交换机类型的接发消息,会对队列、交换机、路由绑定、消息发送的配置和使用有更深的了解,选择类型也更灵活、正确。

2.默认交换机

  • 配置类

    @Configuration
    public class DefaultExchange {
        @Bean
        public Queue defaultQueue(){
            return new Queue("default_queue");
        }
    }
    
  • 消费者

    public class DefaultExConsumer {
        @RabbitListener(queues = "default_queue")
        public void consume(String msg){
            log.info("默认交换机:{}",msg);
        }
    }
    
  • 发送者

    public String sendDefaultMsg(){
            Map<String,Object> map = new HashMap<>();
            map.put("fanout","fanout");
            rabbitTemplate.convertAndSend("default_queue",JSON.toJSONString(map));
            return "OK";
        }
    

3.直连交换机

  • 配置类

    @Configuration
    @Slf4j
    public class DirectRabbitmqConfig {
        @Bean
        public Queue rabbitmqDemoDirectQueue(){
            return new Queue("rabbitmqDemoTopic",true,false,false);
        }
    
        @Bean
        public DirectExchange rabbitmqDemoDirectExchange(){
            return new DirectExchange("rabbitmqDemoDirectExchange",true,false);
        }
    
        @Bean
        public Binding directBinding(){
            return BindingBuilder
                    .bind(rabbitmqDemoDirectQueue())
                    .to(rabbitmqDemoDirectExchange())
                    .with("rabbitmqDemoDirectRouting");
        }
    
    }
    
  • 消费者

    @Component
    @Slf4j
    public class DirectConsumer {
        @RabbitListener(queues = "rabbitmqDemoTopic")
        public void consume(Message message){
            try {
                String msg = new String(message.getBody(),"UTF-8");
                log.info("直连交换机:{}",msg);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            } catch (IOException exception) {
                exception.printStackTrace();
            }
        }
    }
    
  • 发送者

    public String sendDirectMsg(String msg){
            Map<String,Object> map = new HashMap<>();
            map.put("msg",msg);
            rabbitTemplate.convertAndSend(RabbitMqConstant.RABBITMQ_DEMO_DIRECT_EXCHANGE,
                    RabbitMqConstant.RABBITMQ_DEMO_DIRECT_ROUTING, JSON.toJSONString(map));
            return "ok";
        }
    

4.扇形交换机

  • 配置类

    @Configuration
    public class FanoutRabbitMqConfig {
        @Bean
        public FanoutExchange fanoutExchange(){
            return new FanoutExchange("fanout_exchange");
        }
    
        @Bean
        public Queue fanoutQueueFirst(){
            return new Queue("queue_1");
        }
    
        @Bean
        public Binding firstBind(){
            return BindingBuilder
                    .bind(fanoutQueueFirst())
                    .to(fanoutExchange());
        }
    
        @Bean
        public Queue fanoutQueueSecond(){
            return new Queue("queue_2");
        }
    
        @Bean
        public Binding secondBind(){
            return BindingBuilder
                    .bind(fanoutQueueSecond())
                    .to(fanoutExchange());
        }
    }
    
  • 消费者

    • consumer1

      @Component
      @Slf4j
      public class FConsumer1 {
          @RabbitListener(queues = "queue_1")
          public void consume(String message){
              log.info("fanout-consumer1:{}",message);
          }
      }
      
    • consumer2

      @Component
      @Slf4j
      public class FConsumer2 {
          @RabbitListener(queues = "queue_2")
          public void consume(String message){
              log.info("fanout-consumer2:{}",message);
          }
      }
      
  • 发送者

    public String sendFanoutMessage(){
            Map<String,Object> map = new HashMap<>();
            map.put("fanout","fanout");
            rabbitTemplate.convertAndSend(RabbitMqConstant.DEMO_FANOUT_EXCHANGE,JSON.toJSONString(map));
            return "OK";
        }
    

5.主题交换机

概念参考:https://rabbitmq.mr-ping.com/tutorials_with_golang/[5]Topics.html

  • topic交换机的binding key和routing_key有两个特殊应用方式:

    • ·* (星号) 用来表示一个单词.

    • # (井号) 用来表示任意数量(零个或多个)单词。

  • 配置类

    @Configuration
    public class TopicRabbitMqConfig {
        @Bean
        public TopicExchange topicExchange(){
            return new TopicExchange("topic_exchange");
        }
    
        @Bean
        public Queue topicQueue1(){
            return new Queue("topicQueue1");
        }
    
        @Bean
        public Binding topicQueueBinding1(){
            return BindingBuilder.bind(topicQueue1())
                    .to(topicExchange())
                    .with("topic.*");
        }
    
        @Bean
        public Queue topicQueue2(){
            return new Queue("topicQueue2");
        }
    
        @Bean
        public Binding topicQueueBinding2(){
            return BindingBuilder.bind(topicQueue2())
                    .to(topicExchange())
                    .with("topic.msg.*");
        }
    
    }
    
  • 消费者

    • consumer1

      @Component
      @Slf4j
      public class TopicConsumer1 {
          @RabbitListener(queues = "topicQueue1")
          public void consume(Message message){
              String str = new String(message.getBody());
              log.info("主题交换机,队列-topicQueue1的消费者:{}", str);
          }
      }
      
    • consumer2

      @Component
      @Slf4j
      public class TopicConsumer2 {
          @RabbitListener(queues = "topicQueue2")
          public void consume(Message message){
              String str = new String(message.getBody());
              log.info("主题交换机,队列-topicQueue2的消费者:{}", str);
          }
      }
      
  • 发送者

        public void sendTopicMsg(){
            Map<String,Object> map = new HashMap<>();
            map.put("fanout","fanout");
            rabbitTemplate.convertAndSend("topic_exchange","topic.msg.piper",JSON.toJSONString(map));
        }
    

6.头交换机

  • 配置类

    @Slf4j
    @Configuration
    public class HeaderRabbitMqConfig {
        @Bean
        public HeadersExchange headersExchange(){
            return new HeadersExchange("header_exchange");
        }
    
        @Bean
        public Queue headerQueue1(){
            return new Queue("headerQueue1");
        }
    
        @Bean
        public Binding bindToHeaderExchange1(){
            Map<String,Object> headerMap = new HashMap<>();
            headerMap.put("key1","1");
            headerMap.put("key2","3");
            return BindingBuilder.bind(headerQueue1())
                    .to(headersExchange())
                    .whereAny(headerMap).match();
        }
    
        @Bean
        public Queue headerQueue2(){
            return new Queue("headerQueue2");
        }
    
        @Bean
        public Binding bindingToHeaderExchange2(){
            Map<String,Object> headerMap = new HashMap<>();
            headerMap.put("key1","1");
            headerMap.put("key2","2");
            return BindingBuilder.bind(headerQueue2())
                    .to(headersExchange())
                    .whereAll(headerMap).match();
        }
    }
    
  • 消费者

    • consumer1
    @Component
    @Slf4j
    public class HeaderConsumer1 {
        @RabbitListener(queues = "headerQueue1")
        public void consume(String msg){
            log.info("headerQueue1===");
        }
    }
    
    • consumer2

      @Component
      @Slf4j
      public class HeaderConsumer2 {
          @RabbitListener(queues = "headerQueue2")
          public void consume(String msg){
              log.info("headerQueue2===");
          }
      }
      
  • 发送者

        public void sendHeaderMsg(){
            MessageProperties properties = new MessageProperties();
            properties.setHeader("key1","1");
            properties.setHeader("key2","2");
            Message message = new Message("headermessage".getBytes(StandardCharsets.UTF_8),properties);
            rabbitTemplate.convertAndSend("header_exchange",null,message);
        }
    
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值