⑤. service代码以及启动后的效果如下
@Service public class OrderService { @Autowired private RabbitTemplate rabbitTemplate; //1. 发布与订阅模式 public void makeOrder(Long userId, Long productId) { // 1: 模拟用户下单 String orderNumer = UUID.randomUUID().toString(); System.out.println("用户 " + userId + ",订单编号是:" + orderNumer); // 发送订单信息给RabbitMQ fanout rabbitTemplate.convertAndSend("fanout_order_exchange", "", orderNumer); } }
@SpringBootTest class ProducerApplicationTests { @Autowired private OrderService orderService; @Test void contextLoads() { orderService.makeOrder(1L,1L); } }
⑥. 三个消费者代码如下
@Service @RabbitListener(queues = {"email.fanout.queue"}) public class EmailService { @RabbitHandler public void messageRevice(String message){ System.out.println("email----------"+message); } }
@Component @RabbitListener(queues = {"sms.fanout.queue"}) public class SmsService { @RabbitHandler public void messageRevice(String message){ System.out.println("SMS----------"+message); } }