②. SpringBoot案例 - 路由模式
- ①. 生产者代码如下
@Configuration public class DirectRabbitConfig { //1.声明交换机 @Bean public DirectExchange directExchange(){ return new DirectExchange("direct_order_exchange",true,false); } //2.声明队列 @Bean public Queue emailDirectQueue() { return new Queue("email.direct.queue", true); } @Bean public Queue smsDirectQueue() { return new Queue("sms.direct.queue", true); } @Bean public Queue weChatDirectQueue() { return new Queue("weChat.direct.queue", true); } //3.队列和交换机绑定 @Bean public Binding bingDirectEmail(){ return BindingBuilder.bind(emailDirectQueue()).to(directExchange()).with("email"); } @Bean public Binding bingDirectSms(){ return BindingBuilder.bind(smsDirectQueue()).to(directExchange()).with("sms"); } @Bean public Binding bindDirectWeChat(){ return BindingBuilder.bind(weChatDirectQueue()).to(directExchange()).with("weChat"); } }
@Service public class OrderService { @Autowired private RabbitTemplate rabbitTemplate; //2. direct模式 public void makeDirectOrder(Long userId, Long productId) { // 1: 模拟用户下单 String orderNumer = UUID.randomUUID().toString(); System.out.println("用户 " + userId + ",订单编号是:" + orderNumer); // 发送订单信息给RabbitMQ Sms和微信发送消息 rabbitTemplate.convertAndSend("direct_order_exchange", "sms", orderNumer); rabbitTemplate.convertAndSend("direct_order_exchange", "weChat", orderNumer); } }
// Direct模式 @Test public void DirectTest(){ orderService.makeDirectOrder(1L,1L); }
②. 消费者代码如下
@Service @RabbitListener(queues = {"email.direct.queue"}) public class EmailService { @RabbitHandler public void messageDirectRevice(String message){ System.out.println("email direct----------"+message); } }
@Component @RabbitListener(queues = {"sms.direct.queue"}) public class SmsService { @RabbitHandler public void messageDirectRevice(String message){ System.out.println("SMS direct----------"+message); } }
@Component @RabbitListener(queues = {"weChat.direct.queue"}) public class WeixinService { @RabbitHandler public void messageDirectRevice(String message){ System.out.println("weChat direct----------"+message); } }