使用代码生成队列与交换机以及使用

使用代码生成队列与交换机以及使用

一、使用配置类

1.在配置类中使用两种方式创建队列,注意Queue的包

   import org.springframework.amqp.core.Queue;
	 import org.springframework.amqp.core.QueueBuilder;

		@Bean
    public Queue topicQueue1() {
        return new Queue("topic1.queue");
    }

    @Bean
    public Queue topicQueue2() {
        return QueueBuilder.durable("topic2.queue").build();
    }

2.在配置类中创建交换机

    @Bean
    public TopicExchange topicExchange() {
        return ExchangeBuilder.topicExchange("topic.exchange").build();
    }

3.在配置类中交换机与队列进行绑定,绑定多个路由键时,需要写多个方法,而不是在后面接with或在with里写多个参数。

    @Bean
    public Binding topicQueue1ToTopicExchange(Queue topicQueue1, TopicExchange topicExchange) {
        return BindingBuilder.bind(topicQueue1).to(topicExchange).with("#.debu");
    }

二、使用注解

在监听上添加注解内容,相比之前的@RabbitListener(queues = "simple.queue")来说,复杂很多

    @RabbitListener(bindings = {
            @QueueBinding(
                    value = @Queue(name = "topic1.queue"),
                    exchange = @Exchange(name = "topic.exchange", type = ExchangeTypes.TOPIC),
                    key = "#.debu"
            )
    })
    public void getTopicMessage1(String msg) {
        log.info("消费者1号 收到消息:{}", msg);
    }

三、使用

消息生产者

    @Autowired
    private AmqpTemplate amqpTemplate;
		//or
    @Autowired
    private RabbitTemplate rabbitTemplate;

		@Test
    public void sendDirectMessage1() {
        String directExchange = "direct.exchange";
        amqpTemplate.convertAndSend(directExchange, "red", "颜色为red");
        amqpTemplate.convertAndSend(directExchange, "blue", "颜色为blue");
        amqpTemplate.convertAndSend(directExchange, "yellow", "颜色为yellow");
    }
posted @   超级大菠萝面包  阅读(18)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· winform 绘制太阳,地球,月球 运作规律
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· AI与.NET技术实操系列(五):向量存储与相似性搜索在 .NET 中的实现
· 超详细:普通电脑也行Windows部署deepseek R1训练数据并当服务器共享给他人
点击右上角即可分享
微信分享提示