NestJS - Microservices with Redis
Tags: typescript, javascript, beginners, microservices
Published: 2020-03-12 15:31:58

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](https://dev.to/lampewebdev/monorepo-and-microservice-setup-in-nest-js-41n4)

###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:
```bash
sudo apt install redis-server
```
That's it! And Redis Server should also be available on your OS!

Now we need to start Redis.
```bash
#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:
```bash
redis-cli
```
Now you should see something like:
```bash
127.0.0.1:6379>
```

we can now type:
```bash
set test "Hello dev.to!"
```
We Should get an `OK` back from Redis
To retrieve the value we just need to type:
```bash
get test
```
You now should see `Hello dev.to!`. Good, our Redis server is working! Let's exit it with
```bash
exit
```

### Sending messages with Redis in NestJS

First, we need to add the `redis` package to our project with:
```bash
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`

```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`

```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!

![](https://res.cloudinary.com/practicaldev/image/fetch/s--jBHkC61I--/c_limit%2Cf_auto%2Cfl_progressive%2Cq_auto%2Cw_880/https://dev-to-uploads.s3.amazonaws.com/i/0d0cidtg34o15980nfj6.png)

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](https://www.instagram.com/lampewebdev/) | [Twitter](https://twitter.com/lampewebdev) | [LinkedIn](https://www.linkedin.com/in/michael-lazarski-25725a87) | [Medium](https://medium.com/@lampewebdevelopment) | [Twitch](https://dev.to/twitch_live_streams/lampewebdev) | [YouTube](https://www.youtube.com/channel/UCYCe4Cnracnq91J0CgoyKAQ)