Listening to multiple RabbitMQ queues with Nestjs

Viewed 6909

I was looking at Nestjs documentation to set up a microservice that listens to RabbitMQ messages. It's very straight forward when I have to listen to one queue. What if there are multiple queues that my microservice has to listen to? I was using the following method which is done in main.ts file.

await app.connectMicroservice({
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://localhost:5672'],
      queue: 'q-1',
      queueOptions: {
        durable: false
      },
    },
  });

Now that I have more than one queue, I can call another connectMicroservice function to do so. However, when consuming messages in my Controller, there's no way to tell my controller to which queue to listen to (either q-1 or q-2). All I know is that there's a @MessagePattern decorator that can mention what pattern to consume in that function but not sure how to mention the queue name.

2 Answers

The built in NestJS microservices implementation for RabbitMQ is a bit limited when it comes to these types of scenarios.

The @golevelup/nestjs-rabbitmq package was built specifically to address these gaps in functionality. It gives you a better integration that allows you to intuitively interact with multiple RabbitMQ Exchanges and Queues inside of a single NestJS application or microservice. It also aims to provide better support for different messaging patterns like Publish/Subscribe and RPC.

Disclaimer: I'm the author of this package

Simply add code as follows:

await app.connectMicroservice({
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://localhost:5672'],
      queue: 'q-1',
      queueOptions: {
        durable: false
      },
    },
  });
await app.connectMicroservice({
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://localhost:5672'],
      queue: 'q-2',
      queueOptions: {
        durable: false
      },
    },
  });

or an even simpler solution:

for (const queue of ['q-1', 'q-2']) {
  await app.connectMicroservice({
    transport: Transport.RMQ,
    options: {
      urls: ['amqp://localhost:5672'],
      queue,
      queueOptions: {
        durable: false
      },
    },
  });
}
app.startAllMicroservices();
Related