I'm trying to understand how Nest microservices work.
Let's start with this example from the docs (https://docs.nestjs.com/faq/hybrid-application)
const app = await NestFactory.create(AppModule);
// microservice #1
const microserviceTcp = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: {
port: 3001,
},
});
// microservice #2
const microserviceRedis = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.REDIS,
options: {
url: 'redis://localhost:6379',
},
});
await app.startAllMicroservicesAsync();
await app.listen(3001);
After going through the source (https://github.com/nestjs/nest) , I understand connectMicroservice creates a net.Server when using TCP and the server starts listening when startAllMicroservicesAsync is called.
But then app.listen should initialize the listening of the base Nest webserver.
Why doesn't that cause an error?
I checked what happens if I have two microservices connected on the port. It sure does throw an error. What am I missing here?
// CODE CAUSES ERROR AS EXPECTED
const app = await NestFactory.create(AppModule);
// microservice #1
const microserviceTcp = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: {
port: 3001,
},
});
// microservice #2 <--- THIS WILL CAUSE AN ERROR AS EXPECTED
const microserviceTcp = app.connectMicroservice<MicroserviceOptions>({
transport: Transport.TCP,
options: {
port: 3001,
},
});
await app.startAllMicroservicesAsync();
await app.listen(3001);