NestJS - Combine HTTP with RabbitMQ in microservices

て烟熏妆下的殇ゞ 提交于 2019-12-10 23:54:49

问题


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 new Cat, I want an CatCreatedEvent or CatUpdatedEvent 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.


回答1:


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);


来源:https://stackoverflow.com/questions/53995130/nestjs-combine-http-with-rabbitmq-in-microservices

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!