0Pricing
NestJS Enterprise Backend APIs · 강의

NestJS 마이크로서비스 개요

TCP, Redis, RabbitMQ와 같은 다양한 전송 수단을 사용하여 NestJS 마이크로서비스를 설정하고 핵심 개념을 이해합니다.

NestJS 마이크로서비스 개요은(는) CoddyKit의 무료 NestJS Enterprise Backend APIs 강의입니다. 이것은 3개 중 1번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 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 AI 튜터), CoddyKit PRO로 업그레이드하면 NestJS Enterprise Backend APIs 강의 전체를 잠금 해제할 수 있습니다. NestJS Enterprise Backend APIs 강의에는 총 3개의 강의가 포함되어 있습니다.

“NestJS 마이크로서비스 개요”에서 뭘 배우나요?

TCP, Redis, RabbitMQ와 같은 다양한 전송 수단을 사용하여 NestJS 마이크로서비스를 설정하고 핵심 개념을 이해합니다. 브라우저에서 직접 실행하는 실습 코드로 NestJS Enterprise Backend APIs을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

NestJS Enterprise Backend APIs을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 NestJS Enterprise Backend APIs은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 3개 중 1번째 강의입니다.

“NestJS 마이크로서비스 개요” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 NestJS Enterprise Backend APIs 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 NestJS Enterprise Backend APIs 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. NestJS 마이크로서비스 개요
  2. RabbitMQ 통합
  3. 서비스 간 통신
← NestJS Enterprise Backend APIs(으)로 돌아가기