NestJS 마이크로서비스 — Product 로직을 Gateway로 옮기기
1. 목표
Gateway가 Product 관련 요청을 수신합니다.
실제 데이터 생성/조회 로직은 Product 마이크로서비스가 담당합니다.
Gateway는 단순히 API 엔드포인트 역할과 유효성 검증만 담당합니다.
2. 전체 흐름
클라이언트 → Gateway (HTTP 요청)
Gateway ProductController → ProductService 호출
ProductService → Product 마이크로서비스로 TCP 메시지 전송
Product 마이크로서비스 → 요청 처리 후 응답 반환
Gateway → 클라이언트로 결과 전달
3. 코드 흐름과 설명
(1) Gateway ProductController
@Controller('product')
export class ProductController {
constructor(private readonly productService: ProductService) {}
@Post('sample')
createSamples() {
console.log('✅ gateway controller createSamples');
return this.productService.createSamples();
}
}
설명: /product/sample 엔드포인트를 만들고, 요청이 들어오면 Gateway의 ProductService를 호출합니다.
(2) Gateway ProductService
@Injectable()
export class ProductService {
constructor(
@Inject(PRODUCT_SERVICE)
private readonly productMicroservice: ClientProxy,
) {}
async createSamples() {
console.log('✅ gateway createSamples');
return lastValueFrom(
this.productMicroservice.send({ cmd: 'create_samples' }, {}),
);
}
}
설명: ClientProxy.send()를 통해 Product 마이크로서비스로 { cmd: 'create_samples' } 메시지를 보냅니다. 결과는 lastValueFrom()으로 받아 Promise 형태로 반환합니다.
(3) Product 마이크로서비스 Controller
@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);
}
}
설명:
@MessagePattern을 통해 TCP 메시지를 수신합니다.
create_samples 명령 → 샘플 데이터 생성.
get_products_info 명령 → 특정 상품 ID들의 정보를 조회.
RpcInterceptor는 에러 처리와 응답 포맷을 표준화하는 역할을 합니다.
4. 최종 정리
Gateway는 /product/sample HTTP 엔드포인트를 제공하고, 요청을 Product 마이크로서비스로 전달합니다.
Product 마이크로서비스는 TCP 메시지를 받아 실제 비즈니스 로직을 처리합니다.
이로써 Product 관련 로직도 마이크로서비스 아키텍처 구조에 맞게 Gateway와 서비스 간의 분리가 이루어집니다.
5. 체크리스트
Gateway ProductController 작성
Gateway ProductService에서 ClientProxy.send 구현
Product 마이크로서비스 Controller에서 MessagePattern 처리
DTO/ValidationPipe 적용
RpcInterceptor로 응답 표준화
이제 Auth, Product 모두 Gateway를 통해 통신하도록 구조가 완성되었습니다.
다음 단계에서는 Order 로직도 동일한 패턴으로 옮겨 마이크로서비스 전체 구성을 완성할 수 있습니다.













댓글 ( 0)
댓글 남기기