25.03.25 TIL API Gateway

신성훈·2025년 3월 24일

TIL

목록 보기
154/162

API Gateway란?

API Gateway는 클라이언트와 여러 마이크로서비스 사이에서 중앙 집중적인 API 관리 역할을 하는 컴포넌트다. API 요청을 받아 적절한 서비스로 전달하고, 인증, 로드 밸런싱, 캐싱, 로깅 등의 기능을 제공한다.


API Gateway의 주요 기능

1. 요청 라우팅 (Routing)

  • 클라이언트 요청을 특정 마이크로서비스로 전달하는 역할을 한다.
  • 예: /users/1 요청이 User Service로 라우팅됨

2. 로드 밸런싱 (Load Balancing)

  • 여러 서비스 인스턴스로 트래픽을 분산하여 부하를 균형 있게 관리한다.
  • Netflix의 Ribbon, Spring Cloud LoadBalancer 등이 사용될 수 있음

3. 인증 & 인가 (Authentication & Authorization)

  • OAuth 2.0, JWT, API Key 등을 활용하여 보안을 강화한다.
  • 예: 사용자 로그인 후 JWT 토큰을 발급하고 API Gateway에서 검증

4. 캐싱 (Caching)

  • 동일한 요청에 대한 응답을 저장하여 성능을 최적화한다.
  • Redis 또는 in-memory 캐싱을 활용할 수 있음

5. 요청 변환 (Request Transformation)

  • 요청 데이터 형식을 변환하거나, 추가적인 헤더 값을 삽입하는 등의 작업을 수행

6. 모니터링 & 로깅

  • API 호출 기록을 남기고 성능을 추적하는 역할을 한다.
  • ELK(Stack) 또는 Prometheus + Grafana 등의 모니터링 툴과 연계할 수 있음

Spring Cloud Gateway를 활용한 API Gateway 구현

1) 프로젝트 설정

Spring Boot 프로젝트에 아래 의존성을 추가

Gradle

implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'

Maven

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

2) API Gateway 애플리케이션 구성

@SpringBootApplication
@EnableDiscoveryClient
public class ApiGatewayApplication {
    public static void main(String[] args) {
        SpringApplication.run(ApiGatewayApplication.class, args);
    }
}

3) application.yml 설정

spring:
  cloud:
    gateway:
      routes:
        - id: user-service
          uri: lb://USER-SERVICE
          predicates:
            - Path=/users/**
  • /users/** 경로의 API 요청이 USER-SERVICE로 전달됨

4) JWT 기반 인증 필터 추가

API Gateway에서 JWT 토큰을 검증하는 필터를 추가할 수 있다.

@Component
public class JwtAuthFilter extends AbstractGatewayFilterFactory<JwtAuthFilter.Config> {
    public JwtAuthFilter() {
        super(Config.class);
    }

    @Override
    public GatewayFilter apply(Config config) {
        return (exchange, chain) -> {
            String token = exchange.getRequest().getHeaders().getFirst(HttpHeaders.AUTHORIZATION);
            if (token == null || !validateToken(token)) {
                exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
                return exchange.getResponse().setComplete();
            }
            return chain.filter(exchange);
        };
    }

    private boolean validateToken(String token) {
        // JWT 검증 로직
        return true;
    }

    public static class Config {
        // 필터 설정 옵션
    }
}
  • 클라이언트가 요청을 보낼 때, JWT 토큰을 검사하여 인증 여부를 확인한다.

API Gateway를 사용하는 이유

장점

  • 클라이언트가 직접 여러 서비스에 접근하지 않도록 보호할 수 있다.
  • 인증, 로깅, 로드 밸런싱 등의 기능을 중앙에서 관리하여 일관성을 유지할 수 있다.
  • 서비스 변경이 있어도 클라이언트는 API Gateway만 바라보기 때문에 영향도가 적음

단점

  • 단일 장애 지점이 될 수 있음. → 고가용성 아키텍처 필요
  • 네트워크 지연 발생 가능 → 캐싱, 로드 밸런싱 등으로 해결 가능

마무리

API Gateway는 마이크로서비스 아키텍처에서 API 관리를 효율적으로 수행할 수 있도록 도와주는 필수적인 요소다. Spring Cloud Gateway와 같은 도구를 활용하면 쉽게 API Gateway를 구축하고 인증, 로드 밸런싱 등의 기능을 적용할 수 있다.

profile
조급해하지 말고, 흐름을 만들고, 기록하면서 쌓아가자.

0개의 댓글