NestJS 微服务概览
使用 TCP、Redis 和 RabbitMQ 等不同传输器设置 NestJS 微服务,并理解其核心概念。
NestJS 微服务概览 是 CoddyKit 上的免费 NestJS Enterprise Backend APIs 课时。 这是第 1 节课,共 3 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 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 微服务概览」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 NestJS Enterprise Backend APIs 课程的其余内容,请升级到 CoddyKit PRO。 NestJS Enterprise Backend APIs 课程共包含 3 节课。
「NestJS 微服务概览」这节课中我会学到什么?
使用 TCP、Redis 和 RabbitMQ 等不同传输器设置 NestJS 微服务,并理解其核心概念。 你通过在浏览器中直接运行的动手代码来练习 NestJS Enterprise Backend APIs,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 NestJS Enterprise Backend APIs 需要有经验吗?
无需任何先前经验。CoddyKit 上的 NestJS Enterprise Backend APIs 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 1 节课,共 3 节。
「NestJS 微服务概览」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 NestJS Enterprise Backend APIs 课中编写并运行代码吗?
能。每节 NestJS Enterprise Backend APIs 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。
此课程中的所有课时
- NestJS 微服务概览
- RabbitMQ 集成
- 服务间通信