0
0
Lập trình
NM

Hướng Dẫn Sử Dụng Microservices Với Redis Trong NestJS

Đăng vào 2 tuần trước

• 5 phút đọc

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 ServiceNotification 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:

  1. Cài đặt Redis:
    bash Copy
    sudo apt update 
    sudo apt install redis-server 
    sudo systemctl start redis
  2. Cài đặt các gói cần thiết cho dự án NestJS:
    bash Copy
    npm install @nestjs/microservices redis

Bước 2: Tạo User Service

  1. Khởi Tạo Dự Án:
    bash Copy
    nest new user-service
  2. 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:
    typescript Copy
    import { 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:
    typescript Copy
    import { 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);
      }
    }
  3. 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:
    typescript Copy
    import { 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);
      }
    }

Bước 3: Tạo Notification Service

  1. Khởi Tạo Dự Án:
    bash Copy
    nest new notification-service
  2. Lắng Nghe Yêu Cầu Từ Redis:
    • Trong file main.ts, cấu hình service:
    typescript Copy
    import { 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:
    typescript Copy
    import { 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}`;
      }
    }

Bước 4: Kiểm Tra Hệ Thống Microservices

  1. Khởi Động Notification Service:
    bash Copy
    cd notification-service
    npm run start:dev
  2. Khởi Động User Service:
    bash Copy
    cd user-service
    npm run start:dev
  3. Gửi Yêu Cầu Qua Postman hoặc Curl:
    • Gửi thông báo:
    bash Copy
    curl -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:
    Copy
    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

Gợi ý câu hỏi phỏng vấn
Không có dữ liệu

Không có dữ liệu

Bài viết được đề xuất
Bài viết cùng tác giả

Bình luận

Chưa có bình luận nào

Chưa có bình luận nào