How can I check whether a RabbitMQ message queue exists or not?

Viewed 48582

How can I check whether a message Queue already exists or not?

I have 2 different applications, one creating a queue and the other reading from that queue.

So if I run the Client which reads from the queue first, than it crashes.
So to avoid that i would like to check first whether the queue exists or not.

here is the code snippet of how I read the queue:

QueueingBasicConsumer <ConsumerName> = new QueueingBasicConsumer(<ChannelName>); 
<ChannelName>.BasicConsume("<queuename>", null, <ConsumerName>); 
BasicDeliverEventArgs e = (BasicDeliverEventArgs)<ConsumerName>.Queue.Dequeue();
7 Answers

Put below code inside try catch section. If queue or exchange doesn't exist then it will throw error. if exists it will not do anything.

  var channel = connection.CreateModel();


  channel.ExchangeDeclarePassive(sExchangeName);

  QueueDeclareOk ok = channel.QueueDeclarePassive(sQueueName);

   if (ok.MessageCount > 0)
    {
      // Bind the queue to the exchange

     channel.QueueBind(sQueueName, sExchangeName, string.Empty);
    }

There is a meta api in spring-amqp(java implementation)

@Autowired
public RabbitAdmin rabbitAdmin;

//###############get you queue details##############
Properties properties = rabbitAdmin.getQueueProperties(queueName);

//do your custom logic
if( properties == null)
{
    createQueue(queueName);
}

In my humble opinion, best way is to override rabbitmq default configuration.

Main class should disable default rabbit configuration:

    @SpringBootApplication
    @EnableAutoConfiguration(exclude 
  {org.springframework.boot.autoconfigure.amqp.RabbitAutoConfiguration.class})
  public class MyApplication {

    public static void main(String[] args) {
        SpringApplication.run(MyApplication.class, args);
    }

}

my rabbitmq properties are in rabbitmq.properties file:

...
    rabbitmq.queue=my-queue
...

Then just create own configuration rabbitmq component:

@Component
@EnableRabbit
@PropertySource("classpath:rabbitmq.properties")
public class RabbitMQConfiguration
{
...
    @Value("${rabbitmq.queue}")
    private String queueName;

...

    @Bean
    public Queue queue() {
        return new Queue(queueName, false);
    }
...

Also consumer should be setuped:

@Component
@PropertySource("classpath:rabbitmq.properties")
public class MyConsumer
{
    private static Logger LOG = LogManager.getLogger(MyConsumer.class.toString());

    @RabbitListener(queues = {"${rabbitmq.queue}"})
    public void receive(@Payload Object data) {
        LOG.info("Message: " + data) ;
    }

Now when client starts it would automatically create queue if it does not exists. If queue exists it do nothing.

Related