多应用+插件架构,代码干净,二开方便,首家独创一键云编译技术,文档视频完善,免费商用码云13.8K 广告
:-: ![](https://img.kancloud.cn/40/89/4089175e9c64f72de5a97b4cf84ca3eb_1097x284.png) 生产消费过程 **1. 交换机与队列绑定** ```java @Configuration public class RabbitConfig { public final static String FIRST_EXCHAGE = "first.exchange"; public final static String EARTH_QUEUE = "earth.queue"; public final static String MOON_QUEUE = "moon.queue"; /** * 创建Fanout交换机 */ @Bean("firstExchange") public FanoutExchange firstExchange() { return new FanoutExchange(FIRST_EXCHAGE); } /** * 创建earth队列 */ @Bean("earthQueue") public Queue earthQueue() { return new Queue(EARTH_QUEUE); } /** * 创建moon队列 */ @Bean("moonQueue") public Queue moonQueue() { return new Queue(MOON_QUEUE); } /** * earth队列与交换机绑定 */ @Bean public Binding earthBinding(@Qualifier("earthQueue") Queue queue, @Qualifier("firstExchange") FanoutExchange exchange) { return BindingBuilder.bind(queue).to(exchange); } /** * moon队列与交换机绑定 */ @Bean public Binding moonBinding(@Qualifier("moonQueue") Queue queue, @Qualifier("firstExchange") FanoutExchange exchange) { return BindingBuilder.bind(queue).to(exchange); } } ``` **2. 生产者生产消息** ```java @Slf4j @RestController @RequiredArgsConstructor public class ProducerController { final RabbitTemplate rabbitTemplate; @GetMapping("/fanout/produce") public void fanoutProduce() { //convertAndSend(String exchange, String routingKey, Object object) rabbitTemplate.convertAndSend(RabbitConfig.FIRST_EXCHAGE, null, "zhangsan"); log.info("[fanoutProduce|生产了消息]: {}", "zhangsan"); } } ``` **3. 消费者监听队列** ```java @Slf4j @Component public class RabbitMQListener { /** * 监听earth队列 */ @RabbitListener(queues = RabbitConfig.EARTH_QUEUE) public void earthConsume(Message<String> message, Channel channel) { log.info("[earthConsume|收到了消息]: {}", message.getPayload()); } /** * 监听moon队列 */ @RabbitListener(queues = RabbitConfig.MOON_QUEUE) public void moonConsume(Message<String> message, Channel channel) { log.info("[moonConsume|收到了消息]: {}", message.getPayload()); } } ``` **4. 测试结果** ``` : [fanoutProduce|生产了消息]: zhangsan : [moonConsume|收到了消息]: zhangsan : [earthConsume|收到了消息]: zhangsan ```