본문 바로가기
개발 가이드/Spring Cloud

Spring Cloud Gateway 완전 가이드 2

by 플로거 2026. 8. 3.

4. Spring Cloud Gateway 프로젝트 구성

Spring Cloud Gateway 프로젝트는 Spring Boot 기반으로 생성하며 WebFlux 기반으로 동작하기 때문에 Spring MVC와는 다른 구조를 사용합니다.

Maven 의존성 설정

<dependencies>

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


    <dependency>
        <groupId>
            org.springframework.boot
        </groupId>

        <artifactId>
            spring-boot-starter-actuator
        </artifactId>

    </dependency>


</dependencies>

Gradle 설정


dependencies {

    implementation(
      'org.springframework.cloud:
      spring-cloud-starter-gateway'
    )


    implementation(
      'org.springframework.boot:
      spring-boot-starter-actuator'
    )

}

주의사항

Spring Cloud Gateway는 WebFlux 기반입니다. 따라서 Spring MVC의 spring-boot-starter-web 의존성을 함께 추가하면 충돌이 발생할 수 있습니다.

5. Routing 설정

Gateway의 핵심 기능은 클라이언트 요청을 적절한 서비스로 전달하는 Routing입니다.

Routing은 크게 두 가지 방식으로 설정할 수 있습니다.

  • application.yml 기반 설정
  • Java Config 기반 설정

application.yml Route 설정


spring:

  cloud:

    gateway:

      routes:


      - id: user-service

        uri:
          http://localhost:8081

        predicates:

        - Path=/api/users/**



      - id: product-service

        uri:
          http://localhost:8082

        predicates:

        - Path=/api/products/**


위 설정은 다음과 같이 동작합니다.

요청 URL 대상 서비스
/api/users/** User Service
/api/products/** Product Service

Load Balancer Routing

Kubernetes 또는 Eureka 환경에서는 서비스명을 기반으로 Routing합니다.


spring:

 cloud:

  gateway:

   routes:

   - id: order-service

     uri:
       lb://ORDER-SERVICE

     predicates:

     - Path=/api/orders/**

lb:// Prefix를 사용하면 Spring Cloud LoadBalancer가 여러 인스턴스 중 하나를 선택합니다.

6. Predicate 이해하기

Predicate는 Route가 실행될 조건을 정의합니다. Gateway는 요청 정보를 검사한 뒤 조건이 만족될 경우 해당 Route를 실행합니다.

주요 Predicate 종류

Predicate 설명
Path URL Path 기준 라우팅
Method HTTP Method 기준
Header Header 값 기준
Cookie Cookie 값 기준
Query Query Parameter 기준

Path Predicate 예제


predicates:

- Path=/api/**


Method Predicate 예제


predicates:

- Method=GET


Header Predicate 예제


predicates:

- Header=X-API-Version,v1


7. Gateway Filter

Filter는 요청(Request)과 응답(Response) 사이에서 공통 로직을 처리하는 핵심 기능입니다.

Pre Filter

서비스 호출 전에 실행됩니다.

  • 인증 검사
  • Header 추가
  • 로그 생성
  • Trace ID 생성

Post Filter

서비스 응답 이후 실행됩니다.

  • 응답 Header 수정
  • 응답 로그 처리
  • 성능 측정

StripPrefix Filter

Gateway Prefix를 제거하고 Backend 서비스로 전달할 때 사용합니다.


spring:

 cloud:

  gateway:

   routes:

   - id:user-service

     uri:
       lb://USER-SERVICE


     predicates:

     - Path=/user/**


     filters:

     - StripPrefix=1


요청:

/user/api/profile

Backend 전달:

/api/profile

AddRequestHeader Filter


filters:

- AddRequestHeader=
  X-Gateway,true


8. Global Filter 구현

Global Filter는 모든 Route에 공통 적용되는 Filter입니다.

대표적인 활용 사례:

  • 전체 요청 Logging
  • Trace ID 생성
  • 공통 Header 처리
  • 인증 정보 검사

Custom Global Filter 예제


@Component

public class LoggingFilter 
implements GlobalFilter {


@Override

public Mono<Void> filter(

ServerWebExchange exchange,

GatewayFilterChain chain

){


long start =
System.currentTimeMillis();



return chain.filter(exchange)

.then(

Mono.fromRunnable(() -> {


long end =
System.currentTimeMillis();


System.out.println(
"TIME : "
+
(end-start)
);


})


);


}


}

운영 환경 권장

운영에서는 System.out 출력보다 SLF4J + MDC + Trace ID 기반 로그 구조를 사용하는 것이 좋습니다.

다음 편에서 이어집니다.

Spring Cloud Gateway 완전 가이드 3/3

9. Spring Security + JWT 인증
10. CORS 설정
11. Service Discovery
12. WebSocket 지원
13. 장애 처리
14. Actuator + Prometheus 모니터링
15. Kubernetes 운영 가이드

반응형

'개발 가이드 > Spring Cloud' 카테고리의 다른 글

Spring Cloud Gateway 완전 가이드 3  (0) 2026.08.03
Spring Cloud Gateway 완전 가이드  (0) 2026.08.03

댓글