【问题标题】:How to bind to topic with Spring AMQP only if exchange exists?仅当存在交换时,如何使用 Spring AMQP 绑定到主题?
【发布时间】:2020-01-30 20:39:55
【问题描述】:

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

  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.*");
    }
}

【问题讨论】:

    标签: spring spring-amqp spring-rabbit


    【解决方案1】:

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

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

    【讨论】:

      【解决方案2】:

      跳过交换声明bean并忽略绑定声明失败。

      @SpringBootApplication
      public class So59994152Application {
      
          public static void main(String[] args) {
              SpringApplication.run(So59994152Application.class, args);
          }
      
          @Bean
          public Queue queue() {
              return QueueBuilder.durable("MyQueue").build();
          }
      
          @Bean
          public Binding binding(Queue queue, AmqpAdmin admin) {
              ((RabbitAdmin) admin).setIgnoreDeclarationExceptions(true);
              return new Binding("MyQueue", DestinationType.QUEUE, "MyTopicExchange", "purchases.*", null);
          }
      
          @Bean
          public ApplicationRunner runner(CachingConnectionFactory cf) {
              return args -> {
                  cf.createConnection();
                  cf.destroy();
              };
          }
      
      }
      

      如果你没有使用 Spring Boot;在 admin bean 中设置 admin 属性。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-02-04
        • 1970-01-01
        • 2021-09-18
        • 1970-01-01
        • 2015-01-24
        • 1970-01-01
        相关资源
        最近更新 更多