本文只针对订阅/发布模式(Fanout Exchange)的使用。
一、生产者端的队列/交换器配置:
这里只有生产者客户端需要配置,消费者端可无需配置。
@Configuration
public class FanoutRabbitConfig {
@Autowired
private DirectRabbitConfig directRabbitConfig;
/**
* 创建队列
* @return
*/
@Bean
public Queue CustomFanoutQueue() {
return new Queue("CustomFanoutQueue", true);
}
/**
* Fanout 交换器
* @return
*/
@Bean
public FanoutExchange CustomFanoutExchange() {
return new FanoutExchange("CustomFanoutExchange");
}
/**
* 队列与交换器绑定
* @return
*/
@Bean
public Binding FirstFanoutBinding() {
return BindingBuilder.bind(CustomFanoutQueue()).to(CustomFanoutExchange());
}
/**
* 队列与交换器绑定
* 这里将交换器也绑定至其他已绑定过队列中,即一个队列接收多个交换器的消息
* @return
*/
@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) {
HashMap<String, Object> map = 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交换器转发给与他绑定的所有消息队列中去。