首页 > 解决方案 > 仅当存在交换时,如何使用 Spring AMQP 绑定到主题?

问题描述

我需要将队列绑定到主题交换,但是:

  1. 仅当主题存在时
  2. 如果主题存在,请使用现有设置(例如持久、自动删除等)

原因是,我需要一个 3rd 方应用程序来创建他们想要使用的任何设置的交换,我不想修改主题设置。

我通过阅读 RabbitMQ Spring AMQP 教程将下面的代码放在一起。它有效,但如果不存在则创建交换。

@Configuration
public class BeanConfiguration {
    @Bean
    public TopicExchange topic() {
        return new TopicExchange("MyTopicExchange", true, false);
    }

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

    @Bean
    public Binding binding(TopicExchange topicExchange, Queue queue) {
        return BindingBuilder.bind(queue).to(topicExchange).with("purchases.*");
    }
}

标签: springspring-amqpspring-rabbit

解决方案


我通过使用超类方法 setShouldDeclareFalse 找到了一种方法:

    @Bean
    public TopicExchange topic() {
        TopicExchange topicExchange = new TopicExchange("MyTopicExchange", true, false);
        topicExchange.setShouldDeclare(false);
        return topicExchange;
    }


推荐阅读