T_era

API Gateway 구현하기 본문

Programing/Spring

API Gateway 구현하기

블스뜸 2025. 6. 16. 13:53

Spring Cloud Gateway - API Gateway 구현하기

1. API Gateway란?

API Gateway는 클라이언트와 백엔드 서비스 사이에 위치하는 중간 계층으로,

msa로 분산된 api들을 호출하기 위한 하나의 통로라고 보면된다.

다음과 같은 주요 기능을 제공한다:

  • 라우팅: 클라이언트의 요청을 적절한 마이크로서비스로 전달
  • 로드밸런싱: 여러 인스턴스에 요청을 분산
  • 인증/인가: API 접근 제어
  • 요청/응답 변환: 데이터 형식 변환
  • 서킷브레이커: 장애 서비스 격리
  • 모니터링: API 사용량 및 성능 모니터링

2. Spring Cloud Gateway 의존성 설정

build.gradle

plugins {
    id 'java'
    id 'org.springframework.boot' version '3.2.3'
    id 'io.spring.dependency-management' version '1.1.4'
}

ext {
    set('springCloudVersion', "2023.0.0")
}

dependencies {
    // Spring Cloud Gateway
    implementation 'org.springframework.cloud:spring-cloud-starter-gateway'

    // Eureka Client (서비스 디스커버리)
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'

    // Lombok
    compileOnly 'org.projectlombok:lombok'
    annotationProcessor 'org.projectlombok:lombok'
}

dependencyManagement {
    imports {
        mavenBom "org.springframework.cloud:spring-cloud-dependencies:${springCloudVersion}"
    }
}

3. application.yml 설정

기본 설정

server:
  port: 8000

spring:
  application:
    name: api-gateway
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/user-service/**
          filters:
            - StripPrefix=1
        - id: order-service
          uri: lb://ORDER-SERVICE
          predicates:
            - Path=/order-service/**
          filters:
            - StripPrefix=1
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka/

상세 설정 옵션

1. 라우팅 설정

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/user-service/**
            - Method=GET
            - Header=X-Request-Id, \d+
          filters:
            - StripPrefix=1
            - AddRequestHeader=X-Request-Id, ${random.uuid}
            - AddResponseHeader=X-Response-Id, ${random.uuid}

2. 글로벌 필터 설정

spring:
  cloud:
    gateway:
      default-filters:
        - AddRequestHeader=X-Request-Id, ${random.uuid}
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "*"
            allowedMethods: "*"
            allowedHeaders: "*"

3. 서킷브레이커 설정

resilience4j:
  circuitbreaker:
    instances:
      userService:
        failureRateThreshold: 50
        minimumNumberOfCalls: 5
        automaticTransitionFromOpenToHalfOpenEnabled: true
        waitDurationInOpenState: 5s

4. 로깅 설정

logging:
  level:
    org.springframework.cloud.gateway: DEBUG
    org.springframework.http.server.reactive: DEBUG
    org.springframework.web.reactive: DEBUG
    reactor.netty: DEBUG

4. 주요 기능 설명

1. Predicates (조건부 라우팅)

  • Path: URL 경로 기반 라우팅
  • Method: HTTP 메소드 기반 라우팅
  • Header: 헤더 값 기반 라우팅
  • Query: 쿼리 파라미터 기반 라우팅
  • Host: 호스트 기반 라우팅
  • Cookie: 쿠키 값 기반 라우팅

2. Filters (요청/응답 변환)

  • StripPrefix: URL 경로의 앞부분 제거
  • AddRequestHeader: 요청 헤더 추가
  • AddResponseHeader: 응답 헤더 추가
  • RewritePath: URL 경로 재작성
  • SetPath: 경로 설정
  • RedirectTo: 리다이렉트

3. 글로벌 필터

  • 인증/인가: JWT 토큰 검증
  • 로깅: 요청/응답 로깅
  • 모니터링: 메트릭 수집
  • 요청 제한: Rate Limiting

5. 모니터링 및 관리

Actuator 설정

management:
  endpoints:
    web:
      exposure:
        include: "*"
  endpoint:
    health:
      show-details: always

Prometheus 메트릭

management:
  metrics:
    export:
      prometheus:
        enabled: true

6. 보안 설정

SSL/TLS 설정

server:
  ssl:
    enabled: true
    key-store: classpath:keystore.p12
    key-store-password: your-password
    key-store-type: PKCS12

CORS 설정

spring:
  cloud:
    gateway:
      globalcors:
        corsConfigurations:
          '[/**]':
            allowedOrigins: "https://trusted.com"
            allowedMethods: "GET,POST"
            allowedHeaders: "X-Requested-With"
            allowCredentials: true
            maxAge: 3600

7. 성능 최적화

타임아웃 설정

spring:
  cloud:
    gateway:
      httpclient:
        connect-timeout: 1000
        response-timeout: 5s

연결 풀 설정

spring:
  cloud:
    gateway:
      httpclient:
        pool:
          type: elastic
          max-idle-time: 15s
          max-life-time: 60s

이러한 설정들을 통해 안정적이고 확장 가능한 API Gateway를 구축할 수 있다. 실제 구현 시에는 프로젝트의 요구사항에 따라 적절한 설정을 선택하여 사용하면 된다.