本文只针对订阅/发布模式(Fanout Exchange)的使用。
一、生产者端的队列/交换器配置:
这里只有生产者客户端需要配置,消费者端可无需配置。
@Configuration public class FanoutRabbitConfig { @Autowired private DirectRabbitConfig directRabbitConfig; @Bean public Queue CustomFanoutQueue() { return new Queue("CustomFanoutQueue", true); } @Bean public FanoutExchange CustomFanoutExchange() { return new FanoutExchange("CustomFanoutExchange"); } @Bean public Binding FirstFanoutBinding() { return BindingBuilder.bind(CustomFanoutQueue()).to(CustomFanoutExchange()); } @Bean public Binding SecondFanoutBinding() { return BindingBuilder.bind(directRabbitConfig.CustomDirectQueue()).to(CustomFanoutExchange()); } }
二、消费者端的监听消费:
@Component @RabbitListener(queues = "CustomFanoutQueue") public class FanoutConsumer { @RabbitHandler private void process(Map message) { System.out.println("[fanout-consumer-1]从队列 [CustomFanoutQueue] 收到消息:" + message.toString()); } }
三、发送消息到队列:
下面只是调试样例,不涉及业务。
@RequestMapping("/producer") @RestController public class ProducerController { @Autowired private RabbitTemplate rabbitTemplate; @GetMapping("fanout/send") public String sendFanoutMessage() { int i = 0; while(i < 100000) { HashMapmap = new HashMap(); map.put("message_id", UUID.randomUUID()); map.put("message_msg", "这是一条消息数据"); map.put("message_num", ++i); map.put("message_created_time", new Date()); rabbitTemplate.convertAndSend("CustomFanoutExchange", null, map); } return "发送成功"; } }
使用Postman进行模拟消息发送,最终可以看到消息通过Fanout交换器转发给与他绑定的所有消息队列中去。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)