loading...
Cover image for NestJS - Microservices with Redis

NestJS - Microservices with Redis

lampewebdev profile image Michael "lampe" Lazarski ・3 min read

NestJS (3 Part Series)

1) Monorepo and Microservice setup in Nest.js 2) NestJS - Microservices with Redis 3) NestJS - Adding a frontend to the monorepo

Last week we looked at how we can create a Monorepo and setup Microservices that are connected simply via TCP. This post will build upon that post!

So if you missed it click here

Installing Redis

What is Redis:

Redis is an open-source (BSD licensed), in-memory data structure store, used as a database, cache and message broker. It supports data structures such as strings, hashes, lists, sets, sorted sets with range queries, bitmaps, hyperloglogs, geospatial indexes with radius queries and streams.

That's a mouthful. Let's break it down a little bit.

'in-memory' Means that Redis is running and storing everything in RAM. So it can run ultra-fast. 'data structure store' You can replace this with a database. A message broker can receive a message in one format and send it in the appropriate format to a receiver. Imagin 3 people speaking only german one speaking only English and the third person speaks German and English. This third person is like a message broker. He/She translates from English to German and the other way around.

Redis has a lot more functions than just this but we will use it as a message broker.

I'm using WSL(2) for development and installing the Redis server is easy on Ubuntu/Debian. You just need to run:

sudo apt install redis-server

That's it! And Redis Server should also be available on your OS!

Now we need to start Redis.

#On WSL
sudo service redis-server start
#On Ubuntu
sudo systemctl redis-server start

Let us store 'Hello dev.to!' in our Redis database.
For that we can enter the redis-cli. Type:

redis-cli

Now you should see something like:

127.0.0.1:6379>

we can now type:

set test "Hello dev.to!"

We Should get an OK back from Redis
To retrieve the value we just need to type:

get test

You now should see Hello dev.to!. Good, our Redis server is working! Let's exit it with

exit

Sending messages with Redis in NestJS

First, we need to add the redis package to our project with:

yarn add redis

Now that we have Redis installed we just need to change 2 files! Yes in our case only 2! amazing right? So let's do it!

First apps/blog/src/main.ts

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '@nestjs/microservices';
import { Logger } from '@nestjs/common';

const logger = new Logger('Blog');

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

We just changed the transport option from TCP to REDIS and of course, now we need to change the server.

Second apps/lampeweb/src/app.service.ts

import { Injectable } from '@nestjs/common';
import {
  ClientProxyFactory,
  Transport,
  ClientProxy,
} from '@nestjs/microservices';

@Injectable()
export class AppService {
  private client: ClientProxy;

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

  public getHello(): Promise<string> {
    return this.client.send<string, string>('getHello', 'Michael').toPromise();
  }
}

Here again, we are just chaining the ClientProxyFactory.create function to the same values as before. In a bigger project, this should not be hardcoded but rather passed in via env.

We now just need to run our services again and we should see the same message as last time!

I hope you liked that post! If you want a follow-up, please comment, like, and share. So I can know that you are interested in content like that!

πŸ‘‹Say Hello! Instagram | Twitter | LinkedIn | Medium | Twitch | YouTube

NestJS (3 Part Series)

1) Monorepo and Microservice setup in Nest.js 2) NestJS - Microservices with Redis 3) NestJS - Adding a frontend to the monorepo

Posted on by:

lampewebdev profile

Michael "lampe" Lazarski

@lampewebdev

I'm a full-stack web developer. I love to help people.

Discussion

markdown guide