0Pricing
NestJS Enterprise Backend APIs · Lektion

Überblick über NestJS-Microservices

Richten Sie NestJS-Microservices mit verschiedenen Transportern wie TCP, Redis und RabbitMQ ein und verstehen Sie deren grundlegende Konzepte.

Überblick über NestJS-Microservices ist eine kostenlose NestJS Enterprise Backend APIs-Lektion auf CoddyKit. Dies ist Lektion 1 von 3. Du kannst die komplette Lektion unten kostenlos lesen – dann übst du sie direkt im Browser mit einem integrierten Code-Editor und einem KI-Tutor rund um die Uhr. Sie ist Teil des NestJS Enterprise Backend APIs-Lernpfads, und dein Fortschritt wird über Web und CoddyKit-App synchronisiert. Der NestJS Enterprise Backend APIs-Kurs umfasst insgesamt 3 Lektionen.

Teile dieser Lektion wurden noch nicht übersetzt und werden auf Englisch angezeigt.

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!

Häufig gestellte Fragen

Ist die Lektion „Überblick über NestJS-Microservices“ kostenlos?

Ja — der vollständige Text von „Überblick über NestJS-Microservices“ ist hier im Web kostenlos zu lesen. Um sie interaktiv zu üben (integrierter Code-Editor und 24/7 KI-Tutor) und den Rest des NestJS Enterprise Backend APIs-Kurses freizuschalten, upgrade auf CoddyKit PRO. Der NestJS Enterprise Backend APIs-Kurs umfasst insgesamt 3 Lektionen.

Was lerne ich in „Überblick über NestJS-Microservices“?

Richten Sie NestJS-Microservices mit verschiedenen Transportern wie TCP, Redis und RabbitMQ ein und verstehen Sie deren grundlegende Konzepte. Du übst NestJS Enterprise Backend APIs mit praktischem Code, den du direkt im Browser ausführst, und ein 24/7 KI-Tutor beantwortet deine Fragen während du die Lektion bearbeitest.

Brauche ich Erfahrung, um NestJS Enterprise Backend APIs zu starten?

Keine Vorkenntnisse erforderlich. NestJS Enterprise Backend APIs auf CoddyKit ist für Anfänger bis fortgeschrittene Lernende strukturiert, sodass du hier starten oder von Anfang an beginnen und in deinem eigenen Tempo voranschreiten kannst. Dies ist Lektion 1 von 3.

Wie lange dauert die Lektion „Überblick über NestJS-Microservices“?

Die meisten CoddyKit-Lektionen dauern etwa 5–10 Minuten. Jede ist kompakt und interaktiv, sodass du stetig Fortschritte machst und genau dort weitermachst, wo du aufgehört hast – im Web und in der App.

Kann ich in dieser NestJS Enterprise Backend APIs-Lektion Code schreiben und ausführen?

Ja. Jede NestJS Enterprise Backend APIs-Lektion enthält einen integrierten Code-Editor, sodass du echten Code direkt in deinem Browser schreibst und ausführst und sofort KI-Feedback erhältst — ohne lokale Einrichtung erforderlich.

Alle Lektionen in diesem Kurs

  1. Überblick über NestJS-Microservices
  2. RabbitMQ-Integration
  3. Kommunikation zwischen Services
← Zurück zu NestJS Enterprise Backend APIs