0

How to publish message to rabbit MQ where queue details are provided at runtime.

There are many articles on publishing messages but the queues are being mentioned in application properties file.

Aishi
  • 1

1 Answers1

1

If you mean set the queue name at run time you can send messages using RabbitTemplate class and convertAndSend method. (reference)

Assuming your class is something like this:

@Component
public class MessageSender {
    @Autowired
    private RabbitTemplate rabbitTemplate;

    ...

} 

You can add these methods:

public void sendToQueue(String queueName) {
    rabbitTemplate.convertAndSend(queueName, "Hello from Spring!");
}
    
public void sendToExchange(String exchangeName, String routingKey) {
    rabbitTemplate.convertAndSend(exchangeName, routingKey, "Hi exchange!");
}

But if you refer to create the Queue itself at runtime then you need an AmqpAdmin as @Autowired (recommended) or definiting it in every call.

@Autowired
private AmqpAdmin amqpAdmin;

And inside any method you can create a Queue object with desired parammeters (name, durable... anything else)

Something like this:

Queue queue = new Queue(queueName, ...);
amqpAdmin.declareQueue(queue);

If you want to use @Autowiredyou have to create amqpAdmin in a @Bean like this:

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

Is also explained here

J.F.
  • 13,927
  • 9
  • 27
  • 65