Hướng Dẫn Sử Dụng Microservices Với Redis Trong NestJS
Tổng Quan
Microservices đang trở thành một kiến trúc phổ biến trong phát triển ứng dụng, giúp chia nhỏ ứng dụng thành các dịch vụ độc lập. Trong bài viết này, chúng ta sẽ tìm hiểu cách xây dựng một hệ thống microservices sử dụng Redis trong framework NestJS. Chúng ta sẽ xây dựng hai dịch vụ: User Service và Notification Service.
Kịch Bản
Trong ví dụ này, User Service sẽ quản lý thông tin người dùng và gửi yêu cầu đến Notification Service để gửi thông báo tới họ.
Bước 1: Cài Đặt Redis và Các Gói Cần Thiết
Để bắt đầu, hãy đảm bảo rằng Redis đã được cài đặt trên máy của bạn:
- Cài đặt Redis:
bash
sudo apt update sudo apt install redis-server sudo systemctl start redis
- Cài đặt các gói cần thiết cho dự án NestJS:
bash
npm install @nestjs/microservices redis
Bước 2: Tạo User Service
- Khởi Tạo Dự Án:
bash
nest new user-service
- Cấu Hình User Service Để Gửi Yêu Cầu Qua Redis:
- Trong file
main.ts
, cấu hình dịch vụ như sau:
typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; async function bootstrap() { const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { transport: Transport.REDIS, options: { host: '127.0.0.1', port: 6379, }, }); await app.listen(); } bootstrap();
- Trong file
app.service.ts
, implement phương thức gửi thông báo:
typescriptimport { Injectable } from '@nestjs/common'; import { ClientProxy, ClientProxyFactory, Transport } from '@nestjs/microservices'; @Injectable() export class AppService { private client: ClientProxy; constructor() { this.client = ClientProxyFactory.create({ transport: Transport.REDIS, options: { host: '127.0.0.1', port: 6379 }, }); } async sendNotification(data: any) { return this.client.send({ cmd: 'send_notification' }, data); } }
- Trong file
- Tạo Controller Để Gửi Thông Báo:
- Trong file
app.controller.ts
, cấu hình để nhận yêu cầu gửi thông báo:
typescriptimport { Controller, Post, Body } from '@nestjs/common'; import { AppService } from './app.service'; @Controller('user') export class AppController { constructor(private readonly appService: AppService) {} @Post('notify') notifyUser(@Body() data: { userId: string; message: string }) { return this.appService.sendNotification(data); } }
- Trong file
Bước 3: Tạo Notification Service
- Khởi Tạo Dự Án:
bash
nest new notification-service
- Lắng Nghe Yêu Cầu Từ Redis:
- Trong file
main.ts
, cấu hình service:
typescriptimport { NestFactory } from '@nestjs/core'; import { AppModule } from './app.module'; import { MicroserviceOptions, Transport } from '@nestjs/microservices'; async function bootstrap() { const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule, { transport: Transport.REDIS, options: { host: '127.0.0.1', port: 6379, }, }); await app.listen(); } bootstrap();
- Trong file
app.controller.ts
, implement để xử lý yêu cầu thông báo:
typescriptimport { Controller } from '@nestjs/common'; import { MessagePattern } from '@nestjs/microservices'; @Controller() export class AppController { @MessagePattern({ cmd: 'send_notification' }) handleNotification(data: { userId: string; message: string }) { console.log(`Gửi thông báo cho người dùng ${data.userId}: ${data.message}`); return `Thông báo đã được gửi tới người dùng ${data.userId}`; } }
- Trong file
Bước 4: Kiểm Tra Hệ Thống Microservices
- Khởi Động Notification Service:
bash
cd notification-service npm run start:dev
- Khởi Động User Service:
bash
cd user-service npm run start:dev
- Gửi Yêu Cầu Qua Postman hoặc Curl:
- Gửi thông báo:
bashcurl -X POST http://localhost:3000/user/notify -H "Content-Type: application/json" -d '{"userId": "123", "message": "Chào mừng bạn đến với Microservices sử dụng Redis!"}'
- Kết quả trên Notification Service:
Gửi thông báo cho người dùng 123: Chào mừng bạn đến với Microservices sử dụng Redis!
So Sánh Giao Tiếp Qua Redis và TCP/HTTP
Dưới đây là một bảng so sánh giữa giao tiếp qua Redis và giao tiếp qua TCP/HTTP:
Tiêu chí | Giao Tiếp Qua Redis | Giao Tiếp Qua TCP/HTTP |
---|---|---|
Kiểu Giao Tiếp | Pub/Sub, Queue | Request/Response |
Hiệu Năng | Rất cao (được tối ưu với in-memory) | Thấp hơn vì phụ thuộc vào HTTP |
Độ Phức Tạp | Yêu cầu cấu hình Redis | Đơn giản hơn |
Khả Năng Mở Rộng | Dễ dàng với Redis Cluster | Tốt nhưng cần proxy |
Độ Tin Cậy | Có thể mất dữ liệu | Độ tin cậy cao hơn |
Giao Tiếp Bất Đồng Bộ | Hỗ trợ tốt | Khó khăn hơn |
Giám Sát & Ghi Log | Thực hiện hơi phức tạp | Dễ dàng theo dõi |
Chi Phí Hạ Tầng | Cần thêm tài nguyên | Không cần thêm dịch vụ |
Ưu Điểm và Nhược Điểm
Giao Tiếp Qua Redis
- Ưu Điểm:
- Hiệu suất cao.
- Hỗ trợ tốt cho bất đồng bộ.
- Thích hợp cho ứng dụng cần xử lý nhanh.
- Nhược Điểm:
- Cần cấu hình chính xác để tránh mất dữ liệu.
- Khó giám sát hơn so với HTTP.
Giao Tiếp Qua TCP/HTTP
- Ưu Điểm:
- Dễ dàng triển khai.
- Hỗ trợ giao tiếp đồng bộ và dễ quản lý.
- Nhược Điểm:
- Hiệu năng thấp hơn.
- Tốn băng thông nhiều hơn.
Khi Nào Nên Sử Dụng?
- Redis:
- Ứng dụng real-time và yêu cầu xử lý cao.
- TCP/HTTP:
- Ứng dụng RESTful và giao tiếp đồng bộ.
Liên Kết Hữu Ích
- Tham khảo tài liệu chính thức: NestJS
- Kiểm tra demo: User Service, Notification Service
- Xem bài viết gốc tại: trannhatsang.com
source: viblo