Microservice transports help different small services talk to each other easily and reliably.
Microservice transports in NestJS
import { Transport } from '@nestjs/microservices'; const microserviceOptions = { transport: Transport.TCP, // e.g. Transport.REDIS, Transport.NATS, Transport.RMQ, Transport.GRPC options: { // transport-specific options like host, port, queue name }, };
Choose the transport type based on your communication needs.
Each transport has its own options to configure connection details.
const tcpMicroservice = {
transport: Transport.TCP,
options: { host: '127.0.0.1', port: 3001 },
};const redisMicroservice = {
transport: Transport.REDIS,
options: { url: 'redis://localhost:6379' },
};const rmqMicroservice = {
transport: Transport.RMQ,
options: { urls: ['amqp://localhost:5672'], queue: 'main_queue' },
};This example shows how to create a simple NestJS microservice using TCP transport. The service listens on port 4000 for incoming messages from other services.
import { NestFactory } from '@nestjs/core'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; import { AppModule } from './app.module'; async function bootstrap() { // Create a microservice using TCP transport const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { transport: Transport.TCP, options: { host: '127.0.0.1', port: 4000 }, }); await app.listen(); console.log('Microservice is listening on TCP port 4000'); } bootstrap();
Pick the transport that fits your app's needs for speed, reliability, and complexity.
TCP is simple but less flexible; message brokers like RabbitMQ add reliability and features.
Always configure transports with correct host, port, and credentials to avoid connection issues.
Microservice transports let small services communicate in different ways.
Choose transports like TCP, Redis, or RabbitMQ based on your app's needs.
Proper setup helps your app grow and handle many users smoothly.