【问题标题】:Dynamically add new queues, bindings and exchanges as beans动态添加新的队列、绑定和交换作为 bean
【发布时间】:2014-06-16 10:44:11
【问题描述】:

我目前正在开发一个 rabbit-amqp 实施项目,并使用 spring-rabbit 以编程方式设置我的所有队列、绑定和交换。 (spring-rabbit-1.3.4 和 spring-framework 版本 3.2.0)

在我看来,javaconfiguration 类或基于 xml 的配置中的声明都是静态的。我知道如何为队列设置更动态的值(例如名称),交换 或像这样绑定:

@Configuration
public class serverConfiguration {
   private String queueName;
   ...
   @Bean
   public Queue buildQueue() {
    Queue queue = new Queue(this.queueName, false, false, true, getQueueArguments());
    buildRabbitAdmin().declareQueue(queue);
    return queue;
   }
   ...
}

但我想知道是否可以创建未定义数量的 Queue 实例和 将它们注册为 bean,就像注册所有实例的工厂一样。

我不太熟悉 Spring @Bean 注解及其局限性,但我尝试过

@Configuration
public class serverConfiguration {
   private String queueName;
   ...
   @Bean
   @Scope("prototype")
   public Queue buildQueue() {
    Queue queue = new Queue(this.queueName, false, false, true, getQueueArguments());
    buildRabbitAdmin().declareQueue(queue);
    return queue;
   }
   ...
}

要查看 Queue 的多个 bean 实例是否已注册,我调用:

Map<String, Queue> queueBeans = ((ListableBeanFactory) applicationContext).getBeansOfType(Queue.class);

但这只会返回 1 个映射:

name of the method := the last created instance.

是否可以在运行时向 SpringApplicationContext 动态添加 bean?

【问题讨论】:

  • 这听起来像是 JMX 任务。

标签: spring rabbitmq spring-amqp spring-bean spring-rabbit


【解决方案1】:

您可以将 bean 动态添加到上下文中:

context.getBeanFactory().registerSingleton("foo", new Queue("foo"));

但管理员不会自动声明它们;您必须调用 admin.initialize() 来强制它重新声明上下文中的所有 AMQP 元素。

你不会在@Beans 中做这些,只是普通的运行时 java 代码。

【讨论】:

  • 谢谢,这对我帮助很大。
  • @Gary 在 spring-boot 的情况下使用 addQueues 怎么样。在spring-boot的情况下,您能否扩展您的答案并解释详细信息?
  • addQueues 只是将它们添加到容器中,不会导致它们在代理上声明;他们必须在上下文中。在启动应用程序中,您可以通过 @Autowired 或在 main 方法中使用 ConfigurableApplicationContext context = SpringApplication.run(Application.class, args); 获取对应用程序上下文的引用。
猜你喜欢
  • 1970-01-01
  • 2023-04-06
  • 2020-04-30
  • 2018-03-24
  • 2016-05-28
  • 2012-09-17
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多