Springboot集成RabbitMQ之广播模式

广播模式

生产者
交换机 fanout
消息队列
消息队列
消费者
消费者
  1. 添加依赖
<dependency>
       <groupId>org.springframework.boot</groupId>
       <artifactId>spring-boot-starter-amqp</artifactId>
</dependency>
  1. 添加RabbitMQ属性
spring.rabbitmq.host=localhost
spring.rabbitmq.port=5672
spring.rabbitmq.username=guest
spring.rabbitmq.password=guest
  1. 配置两个队列 fanout.a 与 fanout.b
	@Bean
    public Queue fanout_a(){
        return new Queue("fanout.a");
    }
    @Bean
    public Queue fanout_b(){
        return new Queue("fanout.b");
    }
  1. 配置广播交换机 fanoutExchange
	@Bean
    FanoutExchange fanoutExchange(){
        return new FanoutExchange("fanoutExchange");
    }
  1. 把队列(fanout.a,fanout.b)绑定到主题交换机(fanoutExchange)上
	@Bean
    Binding bindingFanoutExchangeA(Queue fanout_a,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanout_a).to(fanoutExchange);
    }
    @Bean
    Binding bindingFanoutExchangeB(Queue fanout_b,FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanout_b).to(fanoutExchange);
    }
  1. 创建两个接收者,绑定创建的两个队列
@Component
@RabbitListener(queues = "fanout.a")
public class FanoutReceiverA {
    @RabbitHandler
    public void process(String message){
        System.out.println("接收者A:"+message);
    }
}
@Component
@RabbitListener(queues = "fanout.b")
public class FanoutReceiverB {
    @RabbitHandler
    public void process(String message){
        System.out.println("接收者B:"+message);
    }

}
  1. 创建个发送方法用来发送消息
@Component
public class FanoutSender {
    @Autowired
    private AmqpTemplate amqpTemplate;
    public void send(String exchange,String message){
        amqpTemplate.convertAndSend(exchange,"",message);
    }

}
  1. 发送测试数据,结果发现,绑定了交换机的所有队列都能接收到这个消息
fanoutSender.send("fanoutExchange","hello");
//运行结果: 接收者B:hello 接收者A:hello	

你可能感兴趣的:(SpringBoot,java-rabbitmq,rabbitmq,spring,boot)