2

In My Scenario I need to create a lots of queues dynamically at run time that is why I don't want to use @Bean instead want to write a function that create queue and I will call it whenever necessary. Here When i use @bean annotation it creates queue on rabbitmq server.

@Bean
public Queue productQueue(final String queueName) {
    return new Queue(queueName);
} 

But with the same code without @Bean

public Queue productQueue(final String queueName) {
    return new Queue(queueName);
}

when call this function doesn't create queue on rabbitmq server

Queue queue = <Object>.productQueue("product-queue");
2
  • What do you want to say by whenever necessary? You want to call it from an external service? Commented Oct 30, 2021 at 4:08
  • @HarryCoder No I will call from internal service Commented Oct 30, 2021 at 5:17

2 Answers 2

3

To create rabbitmq queue Dynamically I used following approach and this is best approach if you also want to create exchanges and bind to queue.

@Autowired
private ConnectionFactory connectionFactory;

@Bean
public AmqpAdmin amqpAdmin() {
 return new RabbitAdmin(connectionFactory);
}

Now you can define a class that creates queue, exchange and bind them

public class rabbitHelper {
  @Autowired
  private RabbitAdmin rabbitAdmin;
  
  public Queue createQueue(String queueName) {
    Queue q  = new Queue(queueName);
    rabbitAdmin.declareQueue(q);
    return q;
  }
 
 public Exchange createExchange(String exchangeName) {
    Exchange exchange  = new DirectExchange(exchangeName);
    rabbitAdmin.declareExchange(exchange);
    return exchange;
  }

public void createBinding(String queueName, String exchangeName, String routingKey) {
    Binding binding = new Binding(queueName, Binding.DestinationType.QUEUE, queueName, routingKey, null);
        rabbitAdmin().declareBinding(binding);
  
  }
}
Sign up to request clarification or add additional context in comments.

Comments

2

The Queue object must be a bean in the context and managed by Spring. To create queues dynamically at runtime, define the bean with scope prototype:

@Bean
@Scope("prototype")
public Queue productQueue(final String queueName) {
    return new Queue(queueName);
} 

and create queues at runtime using ObjectProvider:

@Autowired
private ObjectProvider<Queue> queueProvider;

Queue queue1 = queueProvider.getObject("queueName1");
Queue queue2 = queueProvider.getObject("queueName2");

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.