Springboot集成RabbitMQ【Fanout Exchange】

本文只针对订阅/发布模式(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交换器转发给与他绑定的所有消息队列中去。
在这里插入图片描述

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值