Microservices Discovery : NestJs From Monolithic to Microservices Architecture

Microservices Discovery : NestJs From Monolithic to Microservices Architecture

Hello my friends! ?? I Hope everything is good with you ! Today, I'm excited to talk about Microservices Discovery with NestJS and explore how it increases its power to join the world of microservices architecture. So let’s go !

?? What's Microservices Architecture??

Microservices architecture is an approach to designing and developing software systems as a suite of small, independent services, each running in its own process. Each service is built around a specific business function and can be developed ,tested, deployed with its own database independently ??.

This architecture contrasts with monolithic applications where all functionalities are integrated and run as a single service. Microservices architecture offers several advantages:

?? Scalability: Each service can be scaled independently based on its load.

?? Flexibility: Services can be developed and deployed independently, allowing teams to use different technologies and update services without affecting the whole system.

?? Resilience: The failure of one service doesn’t necessarily bring down the entire system, improving fault tolerance.

But before we dive into NestJS for microservices, let's first explore the challenges faced in traditional microservices architectures and see how NestJS addresses them:

?? Challenges in Traditional Microservices Architecture:

In traditional microservices architecture, developers often face several challenges:

? Service Discovery: As the number of microservices increases, managing and discovering them becomes complex.?

? Inter-service Communication: Efficiently handling communication between services while ensuring reliability and fault tolerance can be tricky.?

? Configuration Management: Each microservice might require different configurations, making it hard to manage them individually.?

? Scalability: Ensuring that the system scales efficiently with increasing load and number of services.

?? NestJS Benefits for Microservices:

Let's break down some benefits and key concepts in NestJS for microservices :

Built-in Microservices Package: NestJS includes a dedicated package for creating microservices,? each responsible for a specific functionality, ensuring better separation and providing support for various transport layers like TCP, Redis, NATS, MQTT, and more.

?? Inter-service Communication: NestJS provides an intuitive way to handle inter-service communication, making it seamless to send and receive messages between microservices.?

?? Configuration Management: Using the ConfigModule in NestJS, you can manage and load different configurations for your services easily.?

?? Message Patterns: NestJS uses message patterns to handle incoming requests and responses between microservices, ensuring a clean and structured communication process.

?? Interceptors and Filters: These allow you to manage and manipulate request/response flows .Add custom logic before or after request handling, transform data, and improve performance with caching and monitoring. And log detailed error information across your microservices.

?? How Interceptors Help with Caching ?

?? Store Results: When a request comes, an interceptor can store the response in a cache.

?? Retrieve Cached Results: For coming next requests, the interceptor can check the cache first and return the cached response if available, avoiding the need to process the request again.

?? How Interceptors Help with Monitoring ?

?? Log Request Processing Time: Measure how long it takes to handle a request from start to finish.

?? Log Request and Response Details: Capture details about incoming requests and outgoing responses for analysis.

?? Identify Performance issues: Detect slow endpoints or operations that need optimization.

?? Example of Microservices Setup in NestJS:

Here’s a quick example of setting up a basic microservice in NestJS:

main.ts (Microservice)

import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app.module';
async function bootstrap() {
 const app = await NestFactory.createMicroservice<MicroserviceOptions>  (AppModule, {
   transport: Transport.TCP,
?});
?await app.listen();
}
bootstrap();        

app.module.ts

import { Module } from '@nestjs/common';
import { ClientsModule, Transport } from '@nestjs/microservices';
import { AppService } from './app.service';
import { AppController } from './app.controller';
@Module({
?imports: [
   ClientsModule.register([
     { name: 'MATH_SERVICE', transport: Transport.TCP },
    ]),
  ],
  controllers: [AppController],
  providers: [AppService],
})
export class AppModule {}        

app.controller.ts:?

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { AppService } from './app.service';
@Controller()
export class AppController {
 constructor(private readonly appService: AppService) {}
  @MessagePattern({ cmd: 'sum' })
   sum(data: number[]): number {
     return this.appService.sum(data);
   }
}        

app.service.ts :?

import { Injectable } from '@nestjs/common';
@Injectable()
export class AppService {
  sum(data: number[]): number {
    return (data || []).reduce((a, b) => a + b, 0);
  }
}        

client.service.ts (example client to communicate with the microservice)

import { Injectable } from '@nestjs/common';
import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices';
@Injectable()
export class ClientService {
  private client: ClientProxy;
   constructor() {
     this.client = ClientProxyFactory.create({
        transport: Transport.TCP,
       options: { host: '127.0.0.1', port: 3001 }
     });
   }
async sendSum(data: number[]) {
  return this.client.send({ cmd: 'sum' }, data).toPromise();
?}
}        

client.module.ts (registering the client service)

import { Module } from '@nestjs/common';
import { ClientService } from './client.service';
@Module({
  providers: [ClientService],
? exports: [ClientService],
})
export class ClientModule {}        

client.controller.ts (controller to use client service)

import { Controller, Get } from '@nestjs/common';
import { ClientService } from './client.service';

@Controller('client')
export class ClientController {
  constructor(private readonly clientService: ClientService) {}
  @Get('sum')
  async getSum(): Promise<number> {
?   const result = await this.clientService.sendSum([1, 2, 3]);
    return result;
  }
}        

client.module.ts (registering the client controller)

import { Module } from '@nestjs/common';
import { ClientService } from './client.service';
import { ClientController } from './client.controller';

@Module({
  providers: [ClientService],
  controllers: [ClientController],
})
export class ClientModule {}        

In this extended example:

  • main.ts sets up the microservice.
  • app.module.ts registers the microservice and client.
  • app.controller.ts defines a controller that listens for messages with the pattern { cmd: 'sum' }.
  • app.service.ts contains the business logic for the microservice.
  • client.service.ts sets up a client to communicate with the microservice.
  • client.module.ts registers the client service.
  • client.controller.ts defines a controller to send a request to the microservice and get the sum.

these files are not all part of the same NestJS project. Instead In a typical microservices architecture, you would have separate NestJS projects for each microservice and possibly a gateway or client that communicates with these microservices.??

So here's how our previous basic example would look:

  1. Microservice Project:

  • main.ts
  • app.module.ts
  • app.controller.ts
  • app.service.ts

  1. Client Project:

  • client.service.ts
  • client.module.ts
  • client.controller.ts

And following the same approach for other services you want to add in your project such as Product Service and Category Service, Order and so on…

So my friends, I hope the post could be useful and Thanks for reading! If you have any ideas, feel free to share them in the comments below. Have a nice day! ??

Sebastian Perez Zuluaga

FullStack Developer | TypeScript, Java, React, Node.js, SQL/NoSQL | Transforming business needs into efficient software solutions

7 个月

Great post! Going from monoliths to microservices is always a bit weird at first, but NestJS is a great way to start. This post is super helpful, thanks for sharing!

要查看或添加评论,请登录

Elhocine AACHIQ的更多文章

社区洞察

其他会员也浏览了