ThinkChat2.0新版上线,更智能更精彩,支持会话、画图、阅读、搜索等,送10W Token,即刻开启你的AI之旅 广告
:-: ![](https://img.kancloud.cn/a6/da/a6da7013ab5013413a7283cb93a774bb_1345x267.jpg) 生产消费过程 **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 public class ProducerController { @Autowired private RabbitTemplate rabbitTemplate; @RequestMapping("/fanout/produce") public void fanoutProduce() { Map<String, Object> msgBody = new HashMap<>(16); msgBody.put("name", "zhangsan"); msgBody.put("age", 25); //convertAndSend(String exchange, String routingKey, Object object) rabbitTemplate.convertAndSend(RabbitConfig.FIRST_EXCHAGE, null, msgBody); log.info("fanoutProduce[生产了消息]:{}", msgBody); } } ``` **3. 消费者** ```java @Slf4j @Service public class ConsumerService { /** * 监听earth队列 */ @RabbitListener(queues = RabbitConfig.EARTH_QUEUE) public void earthConsume(Message<Map<String, Object>> message, Channel channel) { Map<String, Object> msgBody = message.getPayload(); log.info("earthConsume[收到了消息]:{}", msgBody); } /** * 监听moon队列 */ @RabbitListener(queues = RabbitConfig.MOON_QUEUE) public void moonConsume(Message<Map<String, Object>> message, Channel channel) { Map<String, Object> msgBody = message.getPayload(); log.info("moonConsume[收到了消息]:{}", msgBody); } } ``` **4. 测试结果** ``` : fanoutProduce[生产了消息]:{name=zhangsan, age=25} : earthConsume[收到了消息]:{name=zhangsan, age=25} : moonConsume[收到了消息]:{name=zhangsan, age=25} ```