0
0
NestJSframework~5 mins

Redis transport in NestJS

Choose your learning style9 modes available
Introduction

Redis transport helps different parts of a NestJS app talk to each other fast and reliably using Redis. It makes sending messages between services easy.

You want to connect multiple NestJS microservices to work together.
You need a fast way to send messages between services in your app.
You want to use Redis as a message broker for your NestJS app.
You want to build scalable apps where services communicate asynchronously.
You want to handle events or commands across services using Redis.
Syntax
NestJS
import { ClientProxyFactory, Transport } from '@nestjs/microservices';

const client = ClientProxyFactory.create({
  transport: Transport.REDIS,
  options: {
    url: 'redis://localhost:6379',
  },
});

The transport option must be set to Transport.REDIS to use Redis.

The options object includes Redis connection details like the URL.

Examples
Basic Redis client connecting to local Redis server.
NestJS
const client = ClientProxyFactory.create({
  transport: Transport.REDIS,
  options: { url: 'redis://localhost:6379' },
});
Redis client with password and remote server URL.
NestJS
const client = ClientProxyFactory.create({
  transport: Transport.REDIS,
  options: {
    url: 'redis://:password@redis-server:6379',
  },
});
Setting up a NestJS microservice to listen using Redis transport.
NestJS
const server = await app.connectMicroservice({
  transport: Transport.REDIS,
  options: { url: 'redis://localhost:6379' },
});
await app.startAllMicroservices();
Sample Program

This example creates a NestJS microservice that listens for messages with the pattern 'greet' over Redis. When it receives a name, it replies with a greeting.

NestJS
import { Controller } from '@nestjs/common';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { NestFactory } from '@nestjs/core';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

@Controller()
class AppController {
  @MessagePattern('greet')
  greet(@Payload() name: string): string {
    return `Hello, ${name}!`;
  }
}

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppController, {
    transport: Transport.REDIS,
    options: {
      url: 'redis://localhost:6379',
    },
  });
  await app.listen();
  console.log('Microservice is listening using Redis transport');
}

bootstrap();
OutputSuccess
Important Notes

Make sure Redis server is running before starting the microservice.

Use @MessagePattern to listen for specific message patterns.

Redis transport works well for scalable microservice communication.

Summary

Redis transport lets NestJS microservices communicate using Redis as a message broker.

Set transport: Transport.REDIS and provide Redis connection options.

Use @MessagePattern to handle messages sent over Redis.