0Pricing
NestJS Enterprise Backend APIs · Урок

Обзор микросервисов NestJS

Настройте микросервисы NestJS с использованием различных транспортов, таких как TCP, Redis и RabbitMQ, и разберитесь в их основных понятиях.

«Обзор микросервисов NestJS» — бесплатный урок NestJS Enterprise Backend APIs на CoddyKit. Это урок 1 из 3. Ты можешь прочитать весь урок бесплатно ниже — а потом практиковать его прямо в браузере с встроенным редактором кода и ИИ-репетитором 24/7. Это часть пути обучения NestJS Enterprise Backend APIs, и твой прогресс синхронизируется между веб-версией и приложением CoddyKit. Курс NestJS Enterprise Backend APIs содержит 3 уроков всего.

Части этого урока еще не переведены и отображаются на английском.

Intro to NestJS Microservices

Welcome to the world of NestJS Microservices! In this lesson, we'll explore how NestJS helps you build small, independent services that communicate with each other.

Microservices are an architectural style where applications are built as a collection of loosely coupled services. NestJS provides powerful tools to make this easier.

Why Use Microservices?

Adopting a microservice architecture offers several key advantages:

  • Scalability: Individual services can be scaled independently based on their load.
  • Resilience: Failure in one service is less likely to bring down the entire application.
  • Independent Deployment: Services can be developed, deployed, and updated without affecting others.
  • Technology Diversity: Different services can use different technologies if needed.

Core Concepts: Client & Server

In a microservice setup, we typically have:

  • Microservice Server: This is the actual microservice that listens for incoming messages and processes them.
  • Microservice Client: This is any other application or service that wants to communicate with the microservice server. It sends messages and receives responses.

They work together to perform distributed tasks.

Transporters: The Communication Bridge

How do microservice clients and servers communicate? They use transporters. A transporter is the underlying communication protocol or mechanism.

NestJS supports various transporters out of the box:

  • TCP: For direct, point-to-point communication.
  • Redis: A popular in-memory data store, often used as a message broker.
  • RabbitMQ/NATS/Kafka: Robust message queue systems for advanced scenarios.

Setting Up a TCP Microservice Server

Let's create a basic NestJS microservice server using the TCP transporter. This server will listen for messages on a specific port.

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

async function bootstrap() {
  const app = await NestFactory.createMicroservice<MicroserviceOptions>(
    AppModule,
    {
      transport: Transport.TCP,
      options: {
        host: '127.0.0.1',
        port: 8888,
      },
    },
  );
  await app.listen();
  console.log('TCP Microservice is listening on port 8888');
}
bootstrap();

Defining Message Handlers

On the server side, we define message handlers using the @MessagePattern() decorator. This tells NestJS which method should handle a specific message pattern.

Here, we define a handler for a 'sum' command that adds numbers.

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';

@Controller()
export class AppController {
  @MessagePattern({ cmd: 'sum' })
  accumulate(data: number[]): number {
    console.log('Server received sum request:', data);
    return (data || []).reduce((a, b) => a + b, 0);
  }
}

Setting Up a TCP Microservice Client

Now, let's create a client application that can send messages to our TCP microservice server. We use ClientProxyFactory to create a client instance.

import { NestFactory } from '@nestjs/core';
import { ClientProxyFactory, Transport } from '@nestjs/microservices';
import { INestApplicationContext } from '@nestjs/common';

async function bootstrap() {
  const app: INestApplicationContext = await NestFactory.createApplicationContext({});
  const client = ClientProxyFactory.create({
    transport: Transport.TCP,
    options: {
      host: '127.0.0.1',
      port: 8888,
    },
  });

  const pattern = { cmd: 'sum' };
  const payload = [1, 2, 3, 4];

  console.log('Client sending message to microservice...');
  const result = await client.send(pattern, payload).toPromise();
  console.log('Microservice response:', result);

  await app.close();
}
bootstrap();

Request-Response Pattern: send()

The client.send() method is used for a request-response communication pattern. This means the client sends a message and expects a reply from the microservice server.

It returns an Observable, so we typically use .toPromise() to await the response in an async function.

client.send({ cmd: 'sum' }, [1, 2, 3]).toPromise()

Event-Based Pattern: emit()

For event-based communication, where you don't necessarily need a direct response, you can use the client.emit() method.

This is useful for 'fire-and-forget' scenarios like sending notifications or logging events. The client sends the event and continues without waiting for a reply.

client.emit({ cmd: 'user_created' }, { userId: 42, name: 'Alice' });
console.log('User created event emitted.');

Quick Check: Microservice Fundamentals

Which of the following statements are TRUE about NestJS microservices and their components?

Recap: Microservices Overview

Fantastic job! You've taken your first steps into NestJS microservices. We covered:

  • The benefits of microservices for scalability and resilience.
  • Core concepts: microservice clients, servers, and transporters.
  • How to set up basic TCP microservice servers and clients.
  • The difference between request-response (send()) and event-based (emit()) communication patterns.

In upcoming lessons, we'll dive deeper into specific transporters like Redis and RabbitMQ!

Часто задаваемые вопросы

Урок «Обзор микросервисов NestJS» бесплатный?

Да — полный текст урока «Обзор микросервисов NestJS» бесплатно доступен здесь в веб-версии. Чтобы практиковать его интерактивно (встроенный редактор кода и ИИ-репетитор 24/7) и разблокировать остальной курс NestJS Enterprise Backend APIs, подпишись на CoddyKit PRO. Курс NestJS Enterprise Backend APIs содержит 3 уроков всего.

Чему я научусь в уроке «Обзор микросервисов NestJS»?

Настройте микросервисы NestJS с использованием различных транспортов, таких как TCP, Redis и RabbitMQ, и разберитесь в их основных понятиях. Ты практикуешь NestJS Enterprise Backend APIs с помощью реального кода, который запускаешь прямо в браузере, и ИИ-репетитор 24/7 отвечает на твои вопросы во время урока.

Нужен ли мне опыт, чтобы начать NestJS Enterprise Backend APIs?

Предыдущий опыт не требуется. NestJS Enterprise Backend APIs на CoddyKit структурирован для всех уровней — от новичков до продвинутых, поэтому ты можешь начать отсюда или с самого начала и учиться в своем темпе. Это урок 1 из 3.

Сколько времени занимает урок «Обзор микросервисов NestJS»?

Большинство уроков CoddyKit занимают около 5–10 минут. Каждый из них компактный и интерактивный, поэтому ты постоянно делаешь прогресс и продолжаешь с того же места в веб-версии и приложении.

Можно ли писать и запускать код в этом уроке NestJS Enterprise Backend APIs?

Да. Каждый урок NestJS Enterprise Backend APIs включает встроенный редактор кода, поэтому ты пишешь и запускаешь реальный код прямо в браузере и получаешь моментальную обратную связь от AI — локальная установка не требуется.

Все уроки этого курса

  1. Обзор микросервисов NestJS
  2. Интеграция RabbitMQ
  3. Взаимодействие между сервисами
← Назад к NestJS Enterprise Backend APIs