网站首页> 文章专栏> RabbitMQ-声明队列和交换机
RabbitMQ-声明队列和交换机
原创 时间:2024-05-22 10:51 作者:AI智能 浏览量:2749

声明队列和交互机

1716346061049.webp

1716346076019.webp


1,一般都在消费者中创建队列和交换机

在消费者中创建一个FanoutConfiguration

1716346098677.webp

@Configuration
public class FanoutConfiguration {

    @Bean
    public FanoutExchange fanoutExchange(){
//        ExchangeBuilder.fanoutExchange("hmall.fanout2").build();
        return new FanoutExchange("hmall.fanout2");
    }

    @Bean
    public Queue fanoutQueue3(){
//        QueueBuilder.durable("fanout.queue3").build();
        return new Queue("fanout.queue3");
    }

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

    @Bean
    public Queue fanoutQueue4(){
//        QueueBuilder.durable("fanout.queue3").build();
        return new Queue("fanout.queue4");
    }

    @Bean
    public Binding fanoutBinding4(){
        return BindingBuilder.bind(fanoutQueue4()).to(fanoutExchange());
    }

}

可以看见都成功了

1716346132253.webp


2,创建一个Direct交换机

@Configuration
public class DirectConfiguration {

    @Bean
    public DirectExchange directExchange(){
//        ExchangeBuilder.fanoutExchange("hmall.fanout2").build();
        return new DirectExchange("hmall.direct2");
    }

    @Bean
    public Queue directQueue3(){
//        QueueBuilder.durable("fanout.queue3").build();
        return new Queue("direct.queue3");
    }

    @Bean
    public Binding directBinding3(Queue directQueue3,DirectExchange directExchange){
        return BindingBuilder.bind(directQueue3).to(directExchange).with("red");
    }
}

基于注解声明队列和交换机

1716346164987.webp


1,在生产者中的监听器中创建

@Slf4j
@Component
public class SpringRabbitListener {

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dircet.queue3",durable = "true"),
            exchange = @Exchange(name = "hamll.direct1",type = ExchangeTypes.DIRECT),
            key = {"red","blue"}
    ))
    public void listenDircetQueueMessage3(String msg){
        System.out.println("china.# dircet.queue3:" + msg);
    }

    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "dircet.queue4",durable = "true"),
            exchange = @Exchange(name = "hamll.direct1",type = ExchangeTypes.DIRECT),
            key = {"china.#","#.news"}
    ))
    public void listenDircetQueueMessage4(String msg){
        System.out.println("#.news 收到了 dircet.queue4:" + msg);
    }
}

1716346193810.webp

1716346208846.webp



以上配置完成,请动手尝试一下!

1716346228085.webp

动动小手 !!!
来说两句吧
最新评论
  • 方且
    文章干货满满!作者在阐述每个知识点时,都力求详尽且清晰,使得读者可以轻松理解并掌握。此外,文章中还引用了一些具有代表性的代码片段,这些代码既展示了编程的魅力,也使得读者能够更好地理解相关概念和技巧

  • 首席先森
    支持大佬原创好文,内容丰富,排版精美,望大佬回访指点

  • 熊岛
    这篇面经总结的也不错

  • 火影AI
    感谢博主分享的优质好文,内容干货很多,学到了