RabbitMQ - SpringBoot 案例 - direct 模式

Java
337
0
0
2022-04-15
标签   RabbitMQ

项目结构如下

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 模式