// math service
const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, {
transport: Transport.TCP, options: { port: 4000 },
});
@MessagePattern({ cmd: "sum" })
sum(@Payload() nums: number[]) { return nums.reduce((a, b) => a + b, 0); }
// caller
ClientsModule.register([{ name: "MATH", transport: Transport.TCP, options: { port: 4000 } }]);
constructor(@Inject("MATH") private client: ClientProxy) {}
total = await firstValueFrom(this.client.send({ cmd: "sum" }, [1, 2, 3]));
Start the service with NestFactory.createMicroservice(). Call it from another app through a ClientProxy from ClientsModule.register().
The microservice side. createMicroservice() starts an app that listens on a transport instead of HTTP. A transport is the way messages travel. Built-in transports are TCP, Redis, NATS, MQTT, RabbitMQ, Kafka and gRPC. Handlers live in controllers. You decorate them with @MessagePattern() or @EventPattern(), and @Payload() reads the data.
The calling side. ClientsModule.register() creates a ClientProxy under an injection token.
client.send(pattern, data)returns an Observable of the response. It is cold: nothing is sent until you subscribe. You usually subscribe withfirstValueFrom().client.emit()publishes an event and doesn't wait for a reply.
An HTTP app can also host microservice listeners. Call app.connectMicroservice() and then app.startAllMicroservices(). This creates a hybrid application.
createMicroservicestarts an app that listens on a transport.- Handlers use
@MessagePatternor@EventPattern, with@Payload()for the data. ClientsModule.registergives you aClientProxy.send()is cold, so you must subscribe or usefirstValueFrom.connectMicroservicecreates a hybrid HTTP and microservice app.
Read more
- Microservices (https://docs.nestjs.com/microservices/basics)docs.nestjs.com