栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 前沿技术 > 大数据 > 大数据系统

Springboot集成RabbitMQ【Fanout Exchange】

Springboot集成RabbitMQ【Fanout Exchange】

本文只针对订阅/发布模式(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) {
            HashMap 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交换器转发给与他绑定的所有消息队列中去。

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/721594.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号