spring cloud gateway의 route predicate factories

2024. 12. 15. 12:11Spring Microservice

Spring Cloud Gateway의 Route Predicate Factories는 API Gateway의 핵심 기능 중 하나로, 요청이 특정 조건에 부합할 경우 라우트를 활성화하는 역할을 합니다. 이를 통해 클라이언트 요청을 세부적으로 제어하고, 라우팅 로직을 간결하게 구성할 수 있습니다.


1. Route Predicate Factory란 무엇인가?

Spring Cloud Gateway에서 Predicate는 요청이 특정 조건을 만족하는지 검사하는 역할을 합니다. boolean 값을 반환하며, 조건이 true일 경우 라우트가 활성화됩니다. 이러한 Predicate는 Spring Cloud Gateway에서 Route Predicate Factory라는 형태로 미리 정의되어 제공됩니다.

Predicate의 특징

  • 요청(Request)의 여러 속성을 기반으로 동작 (URL 경로, HTTP 메서드, 헤더, 쿠키 등).
  • YAML 파일이나 Java DSL을 통해 선언적으로 설정.
  • 여러 Predicate를 조합하여 복잡한 조건 구성 가능 (AND, OR, NOT).

2. Route Predicate Factory의 동작 원리

구성요소

  • Route: 요청을 처리하기 위한 경로 정보(URI)와 조건(Predicate), 필터(Filter)로 구성.
  • Predicate: 요청이 해당 라우트로 매칭될지를 결정하는 논리적 조건.
  • Filter: 라우트가 매칭된 요청에 대해 추가로 수행되는 로직.

Predicate의 흐름

  1. 클라이언트의 요청이 Gateway로 전달됩니다.
  2. Spring Cloud Gateway는 정의된 라우트와 Predicate를 평가합니다.
  3. Predicate 조건을 만족하는 라우트가 선택되고, 해당 라우트의 필터를 적용한 후 백엔드 서비스로 요청이 전달됩니다.

3. 주요 Route Predicate Factories (상세 설명)

3.1 After Route Predicate

  • 특정 시간 이후에 발생한 요청만 허용.
  • 주로 시간 기반 조건을 설정하는 데 사용.

사용법 (YAML)

routes:
  - id: after_route
    uri: http://example.com
    predicates:
      - After=2024-12-15T10:00:00Z[UTC]

동작 원리

  • 요청의 LocalDateTime이 지정된 시간 이후인지 확인.
  • ISO-8601 형식의 시간 문자열 사용 (2024-12-15T10:00:00Z[UTC]).

예제

  • 특정 시간 이후 API 호출 허용:
    • 2024년 12월 15일 오전 10시 이후에만 /api/sale 경로 허용.

3.2 Before Route Predicate

  • 특정 시간 이전에 발생한 요청만 허용.

사용법

routes:
  - id: before_route
    uri: http://example.com
    predicates:
      - Before=2024-12-31T23:59:59Z[UTC]

예제

  • 연말 이벤트 API /api/event는 12월 31일까지만 허용.

3.3 Between Route Predicate

  • 특정 시간 범위 내의 요청만 허용.

사용법

routes:
  - id: between_route
    uri: http://example.com
    predicates:
      - Between=2024-12-15T10:00:00Z[UTC],2024-12-15T18:00:00Z[UTC]

동작 원리

  • 지정된 두 시간 사이의 요청만 허용.
  • 주로 시간 제한이 필요한 기능에서 유용.

예제

  • 하루 중 특정 시간대(10:00~18:00)에만 API /api/limited 활성화.

3.4 Cookie Route Predicate

  • 요청에 특정 쿠키가 포함된 경우 허용.

사용법

routes:
  - id: cookie_route
    uri: http://example.com
    predicates:
      - Cookie=sessionId,abc123

동작 원리

  • 요청의 특정 쿠키 이름과 값이 일치하는지 확인.
  • 정규식 지원.

예제

  • 로그인 상태 확인:
    • sessionId 쿠키가 특정 값을 가질 때만 /api/profile로 라우팅.

3.5 Header Route Predicate

  • 요청 헤더를 기반으로 라우팅.

사용법

routes:
  - id: header_route
    uri: http://example.com
    predicates:
      - Header=X-Request-Id,^[0-9]+$

동작 원리

  • 지정된 헤더 이름과 값(또는 정규식)이 일치하는 경우 요청 허용.

예제

  • 특정 요청 ID(X-Request-Id)를 가진 요청만 /api/admin으로 라우팅.

3.6 Host Route Predicate

  • 요청의 호스트 이름을 기준으로 라우팅.

사용법

routes:
  - id: host_route
    uri: http://example.com
    predicates:
      - Host=**.example.com

동작 원리

  • 호스트 이름에 대해 와일드카드(**) 지원.
  • 예: api.example.com, www.example.com 모두 허용.

예제

  • 특정 서브도메인 요청 처리:
    • admin.example.com → 관리 서비스로 전달.

3.7 Path Route Predicate

  • 요청 경로를 기준으로 라우팅.

사용법

routes:
  - id: path_route
    uri: http://example.com
    predicates:
      - Path=/api/**, /admin/**

동작 원리

  • 경로 매칭에 와일드카드(**) 사용.
  • 다중 경로 매칭 지원.

예제

  • /api/products/admin/dashboard 요청만 허용.

3.8 Query Route Predicate

  • 요청 쿼리 매개변수를 기준으로 라우팅.

사용법

routes:
  - id: query_route
    uri: http://example.com
    predicates:
      - Query=type,example

동작 원리

  • 쿼리 파라미터의 키와 값이 일치하는 경우 요청 허용.

예제

  • 특정 제품 유형 요청 처리:
    • /api/search?type=electronics 요청만 라우팅.

3.9 RemoteAddr Route Predicate

  • 요청의 클라이언트 IP 주소를 기준으로 라우팅.

사용법

routes:
  - id: remote_addr_route
    uri: http://example.com
    predicates:
      - RemoteAddr=192.168.1.0/24

동작 원리

  • CIDR 형식의 IP 범위와 비교.

예제

  • 내부 네트워크 요청만 허용:
    • IP가 192.168.1.*인 경우에만 라우팅.

3.10 Weight Route Predicate

  • 요청 트래픽을 비율적으로 분배.

사용법

routes:
  - id: weight_route
    uri: http://example1.com
    predicates:
      - Weight=group1,80
  - id: weight_route2
    uri: http://example2.com
    predicates:
      - Weight=group1,20

동작 원리

  • 그룹 내에서 트래픽 비율을 설정.
  • 예: 80% 요청은 example1.com으로, 20% 요청은 example2.com으로 라우팅.

4. Java DSL로 구성

Spring Cloud Gateway는 Java DSL을 사용해 프로그래밍 방식으로 Predicate를 설정할 수 있습니다.

Java DSL 예제

@Bean
public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
        .route("after_route", r -> r
            .after(ZonedDateTime.parse("2024-12-15T10:00:00Z[UTC]"))
            .uri("http://example.com"))
        .route("path_route", r -> r
            .path("/api/**")
            .and()
            .method(HttpMethod.GET)
            .uri("http://example.com"))
        .build();
}

5. 사용자 정의 Predicate

Spring Cloud Gateway는 기본 Predicate 외에도 커스텀 Predicate를 지원합니다.

예제

@Component
public class CustomHeaderRoutePredicateFactory
        extends AbstractRoutePredicateFactory<CustomHeaderRoutePredicateFactory.Config> {

    public CustomHeaderRoutePredicateFactory() {
        super(Config.class);
    }

    @Override
    public Predicate<ServerWebExchange> apply(Config config) {
        return exchange -> {
            String headerValue = exchange.getRequest().getHeaders().getFirst(config.getHeaderName());
            return config.getHeaderValue().equals(headerValue);
        };
    }

    public static class Config {
        private String headerName;
        private String headerValue;
    }
}

결론

Spring Cloud Gateway의 Route Predicate Factories는 라우팅 논리를 유연하고 강력하게 정의할 수 있도록 해주는 핵심 구성 요소입니다. 기본 제공되는 다양한 Predicate를 활용하거나, 사용자 정의 Predicate를 통해 비즈니스 로직에 맞는 라우팅을 설계할 수 있습니다.

'Spring Microservice' 카테고리의 다른 글

Spring Cloud Gateway에서 CORS(Cross-Origin Resource Sharing) 지원  (0) 2024.12.15
Reverse Proxy  (0) 2024.12.15
@CircuitBreaker의 name 속성  (0) 2024.12.12
ring buffer bit  (0) 2024.12.12
bulkhead 패턴  (0) 2024.12.12