Sujit Sharma
Sujit Sharma

Reputation: 130

How to create a rabbitmq Queue in Spring Boot but without using @Bean

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");

Upvotes: 2

Views: 2889

Answers (2)

Ravan
Ravan

Reputation: 54

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);
  
  }
}

Upvotes: 3

gkatiforis
gkatiforis

Reputation: 1652

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");

Upvotes: 2

Related Questions