NestJS - Combine HTTP with RabbitMQ in microservices
RabbitMQ is supported in nestjs as a microservice. If you want your application to support both http requests and a message broker, you can create a hybrid application.
// Create your regular nest application.
const app = await NestFactory.create(ApplicationModule);
// Then combine it with a RabbitMQ microservice
const microservice = app.connectMicroservice({
transport: Transport.RMQ,
options: {
urls: [`amqp://localhost:5672`],
queue: 'my_queue',
queueOptions: { durable: false },
},
});
await app.startAllMicroservicesAsync();
await app.listen(3001);
user2534584
Updated on June 11, 2022Comments
-
user2534584 almost 2 years
I have a few microservices, which are exposed through an API-Gateway. The gateway takes care of handling authentication and routing into the system. The services behind the gateway are mostly simple CRUD-Services. Each service exposes its own API and they communicate synchronously via HTTP. All of these services, including the API-Gateway, are "default" NestJS applications.
Let's stick with the Cats example. Whenever the
Cat-Service
updates or creates a newCat
, I want anCatCreatedEvent
orCatUpdatedEvent
to be emmited. The event should be pushed into some message broker like RabbitMQ and another service should listen to this event and process the event asynchronously.I am not sure how to achive this, in terms of how to "inject" RabbitMQ the right way and I am wondering if this approach makes sense in generel. I have seen the CQRS Module for NestJS, but i think CQRS is a bit too much for this domain. Especially because there is no benefit in this domain to split read- and write-models. Maybe I am totally on the wrong track, so I hope you can give me some advises.
-
user2534584 over 5 yearsThank you! After a bit of trying, I got this working. In the
CatService
I added this, which is called by theCatController
after a POST request to/cats
emitCatCreatedEvent() { return this.client.send({ name: 'catCreatedEvent'}, 'something happend').toPromise(); }
Would you say this approch goes in the right direction? -
Kim Kern over 5 yearsYes, looks good. :-) It's a bit tricky to understand how to use
this.client
. -
Pulak Kanti Bhattacharyya about 5 years@user2534584 can you please share your example?
-
Carmine Ingaldi almost 5 yearsYes, and obiviously the emitCatCreatedEvent() call should always be the last thing done on the happy path, since signals that the "cat creation" is actually happened. Maybe it could be better if the event signalling is done on a controller level, since it looks like more application logic than business logic. Am I wrong?
-
BeetleJuice over 4 years@user2534584 in your post above, where does
this.client
come from? Is that a standard NestJS service? A node driver for RabbitMQ? -
BeetleJuice over 4 yearsnvm; I think it is a
ClientProxy
from docs.nestjs.com/microservices/basics#client