gpt4 book ai didi

spring - 动态添加新的队列、绑定(bind)和交换作为 bean

转载 作者:IT老高 更新时间:2023-10-28 13:47:11 25 4
gpt4 key购买 nike

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

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

@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?

最佳答案

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

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

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

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

关于spring - 动态添加新的队列、绑定(bind)和交换作为 bean,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24241880/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com