在我的場景中,我需要在運行時動態創建大量佇列,這就是為什么我不想使用 @Bean 而是想撰寫一個創建佇列的函式,我會在必要時呼叫它。在這里,當我使用 @bean 注釋時,它會在 rabbitmq 服務器上創建佇列。
@Bean
public Queue productQueue(final String queueName) {
return new Queue(queueName);
}
但是使用相同的代碼沒有@Bean
public Queue productQueue(final String queueName) {
return new Queue(queueName);
}
呼叫此函式時不會在 rabbitmq 服務器上創建佇列
Queue queue = <Object>.productQueue("product-queue");
uj5u.com熱心網友回復:
該Queue物件必須是背景關系中的 bean 并由 Spring 管理。要在運行時動態創建佇列,請定義具有作用域的 bean prototype:
@Bean
@Scope("prototype")
public Queue productQueue(final String queueName) {
return new Queue(queueName);
}
并在運行時使用ObjectProvider以下方法創建佇列:
@Autowired
private ObjectProvider<Queue> queueProvider;
Queue queue1 = queueProvider.getObject("queueName1");
Queue queue2 = queueProvider.getObject("queueName2");
轉載請註明出處,本文鏈接:https://www.uj5u.com/caozuo/344086.html
