RabbitMQ消息中间件广播模式和work模式(竞争模式)使用

work模式

        竞争模式就是两个队列竞争者去消费生产者的消息,通过轮询的方式去消费消息

work模式的使用

1:声明生产者

        发送需要处理的消息,通过生产者产生消息。

@Component
public class WorkProduct {

    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String msg){
        System.out.println("workProduce"+msg);
        rabbitTemplate.convertAndSend("workQueue",msg);
    }
}

2:声明对列

        通过队列去接受生产者产生的消息。

  @Bean
    public Queue workQueue(){
        return new Queue("workQueue");
    }

3:声明消费者

        消费者通过竞争的模式去处理生产者产生的消息。

@Component
public class WorkConsume {
    /**
     * 消费队列中消息中方法
     */
    @RabbitListener(queues = "workQueue") 
    public void reviceA(String msg){
        System.out.println("消费者接收到的消息A:"+msg);

    }

    @RabbitListener(queues = "workQueue") 
    public void reviceB(String msg){
        System.out.println("消费者接收到的消息B:"+msg);

    }
}
广播模式

        通过交换机使队列接收到消息

广播模式的使用

          1:声明生产者

@Component
public class FanoutProduct {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    public void send(String msg){
        rabbitTemplate.convertAndSend("fanoutExchange",null,msg);
    }
}

          2:交换机和队列的声明

                并且实交换机与队列进行绑定32

 /**
     * 广播模式
     * 成员:一个生产者  , 一个交换机, 两个队列,两个消费者
     */
    @Bean
    public Queue fanoutQueueA(){
        return new Queue("fanoutQueueA");
    }
    @Bean
    public Queue fanoutQueueB(){
        return new Queue("fanoutQueueB");
    }
    @Bean
    public FanoutExchange fanoutExchange(){
            return new FanoutExchange("fanoutExchange");
    }

    /**
     * 绑定交换机与队列
     */
    @Bean
    public Binding fanoutQueueAToFanoutExchange(Queue fanoutQueueA,
                                                FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueueA).to(fanoutExchange);
    }

    @Bean
    public Binding fanoutQueueBToFanoutExchange(Queue fanoutQueueB,
                                                FanoutExchange fanoutExchange){
        return BindingBuilder.bind(fanoutQueueB).to(fanoutExchange);
    }

3:消费者的声明

@Component
public class FanoutConsume {

    
        @RabbitListener(queues = "fanoutQueueA")
        public void reviceA(String msg){
                System.out.println("fanoutQueueA:"+msg);
        }


        @RabbitListener(queues = "fanoutQueueB")
        public void reviceB(String msg){
                System.out.println("fanoutQueueB:"+msg);
        }
}

  • 6
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值