Nodejs

 

 

1. Product Proto 정의 (proto 파일)

상품과 관련된 gRPC 서비스를 정의하기 위해 product.proto 파일을 작성합니다.

syntax = "proto3";

package product;

service ProductService {
    rpc CreateSamples(CreateSamplesRequest) returns (CreateSamplesResponse);
    rpc GetProductsInfo(GetProductsInfoRequest) returns (GetProductsInfoResponse);
}

message CreateSamplesRequest {

}

message CreateSamplesResponse {
    bool success = 1;
}

message GetProductsInfoRequest {
    repeated string productIds = 1;
}

message GetProductsInfoResponse {
    message ProductInfo {
        string id = 1;
        string name = 2;
        string description = 3;
        float price = 4;
        uint32 stock = 5;
    }

    repeated ProductInfo products = 1;
}
  • CreateSamples: 샘플 데이터를 생성

  • GetProductsInfo: 여러 상품 ID에 대한 상세 정보를 조회

 

2. NestJS에서 Product Service 구현

NestJS는 gRPC 요청을 @MessagePattern으로 매핑하여 처리합니다.

 ProductController

import {
  Controller,
  UseInterceptors,
  UsePipes,
  ValidationPipe,
} from '@nestjs/common';
import { ProductService } from './product.service';
import { MessagePattern, Payload } from '@nestjs/microservices';
import { GetProductsInfo } from './dto/get-products-info.dto';
import { RpcInterceptor } from '@app/common/interceptor';

@Controller('product')
export class ProductController {
  constructor(private readonly productService: ProductService) {}

  @MessagePattern({ cmd: 'create_samples' })
  @UsePipes(ValidationPipe)
  @UseInterceptors(RpcInterceptor)
  createSamples() {
    console.log('product microservice Controller createSamples');
    return this.productService.createSamples();
  }

  @MessagePattern({ cmd: 'get_products_info' })
  @UsePipes(ValidationPipe)
  @UseInterceptors(RpcInterceptor)
  getProductsInfo(@Payload() data: GetProductsInfo) {
    console.log('getProductsInfo');
    return this.productService.getProductsInfo(data.productIds);
  }
}
  • create_samples: 샘플 데이터를 생성하는 gRPC 요청 처리

  • get_products_info: 상품 ID 배열을 받아 여러 상품 정보를 반환

 

 DTO 정의

import { IsArray, IsNotEmpty, IsString } from 'class-validator';

export class GetProductsInfo {
  @IsArray()
  @IsNotEmpty()
  @IsString({ each: true })
  productIds: string[];
}
  • @IsArray() → 반드시 배열 형태여야 함

  • @IsNotEmpty() → 비어 있지 않아야 함

  • @IsString({ each: true }) → 배열의 각 원소가 문자열인지 검증

 

 

3. gRPC Product Proto 성능 최적화 전략

  1. repeated 필드 활용: 여러 상품 ID를 한 번에 요청하여 네트워크 호출 최소화

  2. DTO 유효성 검사: 잘못된 상품 ID 요청을 초기에 차단

  3. Interceptor 적용: 로깅, 에러 처리, 성능 모니터링 일원화

  4. 서비스 단위 분리: Product Service를 독립적으로 배포 및 확장 가능

 

 

 

about author

PHRASE

Level 60  라이트

나는 내 평생에 하느님에 대한 믿음을 전혀 갖고 있지 않은 사람을 한번도 본 일이 없다. 그 대신 내가 만난 대부분의 사람들은, 말하자면 '마음의 안정을 찾지 못한 사람들'이었다고 여겨진다. -도스토예프스키

댓글 ( 0)

댓글 남기기

작성