RabbitMQ - SpringBoot 案例 - direct 模式

HuDu發表於2021-06-08

專案結構如下

RabbitMQ - SpringBoot 案例 - direct 模式

config 配置

@Configuration
public class DirectRabbitMqConfiguration {
    @Bean
    public DirectExchange directExchange() {
        return new DirectExchange("direct_order_exchange",true,false);
    }

    @Bean
    public Queue directSmsQueue() {
        return new Queue("sms.direct.queue",true);
    }
    @Bean
    public Queue directEmailQueue() {
        return new Queue("email.direct.queue",true);
    }
    @Bean
    public Queue directWeChatQueue() {
        return new Queue("weChat.direct.queue",true);
    }

    @Bean
    public Binding directSmsBinding() {
        return BindingBuilder.bind(directSmsQueue()).to(directExchange()).with("sms");
    }

    @Bean
    public Binding directEmailBinding() {
        return BindingBuilder.bind(directEmailQueue()).to(directExchange()).with("email");
    }

    @Bean
    public Binding directWeChatBinding() {
        return BindingBuilder.bind(directWeChatQueue()).to(directExchange()).with("weChat");
    }

}

服務層

@Service
@RabbitListener(queues = {"email.direct.queue"})
public class DirectEmailConsumer {
    @RabbitHandler
    public void receiveMessage(String message) {
        System.out.println("email direct--接收到的訂單資訊是:->" + message);
    }
}

@Service
@RabbitListener(queues = {"sms.direct.queue"})
public class DirectSMSConsumer {
  @RabbitHandler
  public void receiveMessage(String message) {
  System.out.println("sms direct--接收到的訂單資訊是:->" + message);
  }
}

@Service
@RabbitListener(queues = {"weChat.direct.queue"})
public class DirectWeChatConsumer {
  @RabbitHandler
  public void receiveMessage(String message) {
  System.out.println("weChat direct--接收到的訂單資訊是:->" + message);
  }
}

生產者測試程式碼

public void makeOrderDirect(String userId,String productId,int num) {
        // 1:根據id查詢商品是否充足
        // 2:儲存訂單
        String orderId = UUID.randomUUID().toString();
        System.out.println("訂單生成成功:"+orderId);
        // 3:通過 MQ 來完成訊息的分發
        // 交換機,路由 key/queue 佇列名稱,訊息內容
        String exchangeName = "direct_order_exchange";
        rabbitTemplate.convertAndSend(exchangeName,"sms",orderId);
       rabbitTemplate.convertAndSend(exchangeName,"email",orderId);
}
@Test
void contextLoads() {
      orderService.makeOrderDirect("1","1",12);
}

測試結果如下

RabbitMQ - SpringBoot 案例 - direct 模式

繫結關係如下

RabbitMQ - SpringBoot 案例 - direct 模式

本作品採用《CC 協議》,轉載必須註明作者和本文連結

相關文章