作为bean动态添加新的队列,绑定和交换 [英] Dynamically add new queues, bindings and exchanges as beans
问题描述
我目前正在研究Rabbit-amqp实施项目,并使用spring-rabbit以编程方式设置我所有的队列,绑定和交换. (spring-rabbit-1.3.4和spring-framework版本3.2.0)
I'm currently working on a rabbit-amqp implementation project and use spring-rabbit to programmatically setup all my queues, bindings and exchanges. (spring-rabbit-1.3.4 and spring-framework versions 3.2.0)
在我看来,javaconfiguration类或基于xml的配置中的声明都非常静态.我知道如何为队列设置更动态的值(例如名称),交换 或像这样绑定:
The declaration in a javaconfiguration class or xml-based configuration are both quite static in my opinion declared. I know how to set a more dynamic value (ex. a name) for a queue, exchange or binding like this:
@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就像工厂注册其所有实例一样.
But I was wondering if it was possible to create a undefined amount instances of Queue and register them as beans like a factory registering all its instances.
我对Spring @Bean批注及其局限性不是很熟悉,但是我尝试了
I'm not really familiar with the Spring @Bean annotation and its limitations, but I tried
@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实例:
And to see if the multiple beans instances of Queue are registered I call:
Map<String, Queue> queueBeans = ((ListableBeanFactory) applicationContext).getBeansOfType(Queue.class);
但这只会返回1个映射:
But this will only return 1 mapping:
name of the method := the last created instance.
是否可以在运行时动态地将bean添加到SpringApplicationContext?
Is it possible to dynamically add beans during runtime to the SpringApplicationContext?
推荐答案
您可以将bean动态添加到上下文中:
You can add beans dynamically to the context:
context.getBeanFactory().registerSingleton("foo", new Queue("foo"));
,但是管理员不会自动声明它们;您将必须调用admin.initialize()
强制其重新声明上下文中的所有AMQP元素.
but they won't be declared by the admin automatically; you will have to call admin.initialize()
to force it to re-declare all the AMQP elements in the context.
您不会在@Bean
中执行任何一项操作,而只是正常的运行时Java代码.
You would not do either of these in @Bean
s, just normal runtime java code.
这篇关于作为bean动态添加新的队列,绑定和交换的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!