0
0
NestJSframework~5 mins

Microservice transports in NestJS

Choose your learning style9 modes available
Introduction

Microservice transports help different small services talk to each other easily and reliably.

When you want to split a big app into smaller parts that work independently.
When services need to send messages or data to each other quickly.
When you want to choose the best way for services to communicate, like using HTTP or messaging queues.
When you want to make your app easier to grow and fix without stopping everything.
When you want to handle many users or requests without slowing down.
Syntax
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.

Examples
Use TCP transport for simple direct communication between services.
NestJS
const tcpMicroservice = {
  transport: Transport.TCP,
  options: { host: '127.0.0.1', port: 3001 },
};
Use Redis transport for pub/sub messaging with Redis server.
NestJS
const redisMicroservice = {
  transport: Transport.REDIS,
  options: { url: 'redis://localhost:6379' },
};
Use RabbitMQ transport for reliable message queues.
NestJS
const rmqMicroservice = {
  transport: Transport.RMQ,
  options: { urls: ['amqp://localhost:5672'], queue: 'main_queue' },
};
Sample Program

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.

NestJS
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();
OutputSuccess
Important Notes

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.

Summary

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.