RabbitMQ | Dynamic Queue and Consumer | Grails 2.X

kavita bora
1 min readNov 23, 2020

Here I am going to describe how we can implement dynamic queue and consumer with RabbitMQ and Grails 2.X

In my project I have a client requirement where our client have multi tenant architecture. And he wants to set a new queue and its consumer for each tenant.

If we look a solution for it in spring boot we will easily get so many articles to achieve it.

But in grails It is little bit hard to find a proper blog on it.

So in grails 2.X as we use org.grails.plugins:rabbitmq-native:3.1.3 plugin in BuildConfig.groovy

With this plugin we have most important bean com.budjb.rabbitmq.RabbitContext which gives us the flexibility to perform action on runtime.

Here is code base how we can use this bean -

com.rabbitmq.client.impl.recovery.AutorecoveringConnection connection = rabbitContext.getConnection()Map<String, RecordedQueue> recordedQueueMap = connection.recordedQueues  

String exchangeName = "exchangeName"
String queueName = "newQueue"
String routingKey1 = 'rout'
boolean autoAck = false
if(!recordedQueueMap.containsKey(queueName)) {
com.rabbitmq.client.Channel channel = rabbitContext.createChannel()
channel.exchangeDeclare(exchangeName, "direct", true); channel.queueDeclare(queueName, true, false, false, null); channel.queueBind(queueName, exchangeName, routingKey1); com.rabbitmq.client.DefaultConsumer dynamicConsumer = new com.rabbitmq.client.DefaultConsumer(channel) {
@Override
public void handleDelivery(String consumerTag, com.rabbitmq.client.Envelope envelope, com.rabbitmq.client.AMQP.BasicProperties properties, byte[] body) throws IOException {
String routingKey = envelope.getRoutingKey(); String contentType = properties.getContentType(); long deliveryTag = envelope.getDeliveryTag(); // (process the message components here ...) println(">>>>>>>> " + SerializationUtil.deserialize(body)) channel.basicAck(deliveryTag, false);
}
}
channel.basicConsume(queueName, autoAck, "myConsumerTag", dynamicConsumer)}

Here for dynamic consumer we have written anonymous class. We can make our separate class but it should be a subclass of com.rabbitmq.client.DefaultConsumer .

--

--