Framework/Spring

Spring Cloud Gateway 3.1.0

FreeEnd 2022. 1. 18. 22:43
반응형

본 문서는 3.1.0 버젼을 기준으로 번역 되었습니다.

 

1. Spring Cloud Gateway 

 Spring Cloud Gateway 는 Spring 5, Spring Boot2, 그리고 Project Reactor 를 포함한 Spring 생태계를 기반으로 구축 되었다. Spring Cloud Gateway는 단순하게 제공되고, 효과적인 방법으로 라우팅되며, 모니터링, 메트릭, 복원력등 크로스컷 관심사를 제공하는데 목표를 둡니다.

 

2. 용어

 Route (라우트, 경로) : 게이트웨이의 기본 단위입니다. ID, 목적지 URI, 서술어 모음 (predicates) , 필터 모음 (filters),  등으로 정의 됩니다. 라우트가 일치하면 해당 요건을 처리 하게 됩니다.

 Predicate (프레디케이트, 조건부) : Java 8의 함수 술어부분입니다. 입력 유형은 Spring Framework ServerWebExchange 입니다. 조건부를 이용해 HTTP 리퀘스트의 파라메터, 헤더를 비교 합니다.

 Filter (필터) : GatewayFilter 의 인스턴스로, 특정 팩토리로 구성되어 있습니다. 이를 이용해 DownSteam request 를 보내기전, 후 Request, Response 를 수정할 수 있습니다.

 

 

3. 어떻게 동작 하는가?

다음은 Spring cloude 가 동작하는 방식에 대한 다이어 그램이다.

 

 클라이언트는 Spring Cloud Gateway 에 Request 를 요청 합니다. 만얀 Gateway Handler Mapping 에서 Route 와 리퀘스트가 매칭한다고 판단한다면 이 리퀘스트를 Gateway Web Handler 로 보냅니다. 이 핸들러는 리퀘스트를 해당 필터와 관련된 필터 채인을 통해 수행 합니다. 프록시 서비스 전 pre 필터가 수행되고, 수행 후는 post 필터가 수행 되기 떄문입니다.

 

4. Route 조건부 요소와 필터 요소

 조건부와 필터를 정의 하는데는 두가지방법이 있습니다. 

 4.1 shortcut coinfiguration

 요약 설정 방식은 필터이름에 의해 설정되며, = 로 지정하며, 각 값은 콤마(,) 로 분리 됩니다.

 
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - Cookie=mycookie,mycookievalue

 

 4.2 fully expanded arguments 

전체 확장 설정 방식은 yaml 방식에 좀더 표준되게 이름/값 으로 나타 냅니다. 

 
spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - name: Cookie
          args:
            name: mycookie
            regexp: mycookievalue

 

 

5. 라우팅 서술 요소

Spring Cloud Gateway는 Spring WebFlux HandlerMapping 인프라의 일부로 경로를 일치시킵니다.  Spring Cloud Gateway는 라우팅 조건 요소 를 많이 내장 하고 있습니다. 이러한 서술어들은 다른 http 리퀘스트 요소들을 매치시킵니다. 여러분은 논리적이고 문법적인 많은 요소들을 결합할 수 있습니다.

 

5.1 특정 일시 이후 

Ater 라우트 조건은 특정시작 이후로 매칭할 수 있는 조건절 입니다. 날짜 하나의 매개 변수만 가지며, 지정된 시간 이후에 발생한 리퀘스트만 일치 할 수 있게 지정 할 수 있습니다.

spring:
  cloud:
    gateway:
      routes:
      - id: after_route
        uri: https://example.org
        predicates:
        - After=2017-01-20T17:42:47.789-07:00[America/Denver]

 

5.2  특정 시작 전

Ater 라우트 조건은 특정시작 이전으로 매칭할 수 있는 조건절 입니다. 날짜 하나의 매개 변수만 가지며, 지정된 시간 이전에 발생한 리퀘스트만 일치 할 수 있게 지정 할 수 있습니다.

  cloud:
    gateway:
      routes:
      - id: before_route
        uri: https://example.org
        predicates:
        - Before=2017-01-20T17:42:47.789-07:00[America/Denver]

 

5.3 특정시간 사이

 between 라우트 조건은 두개의 파라메터를 받으며, 첫번째 datetime1 과 두번째 datetime2 사이의 시간사이를 매칭할 수 있는 조건 절 입니다. datetime1 이후, datetime2 이전에 발생한 리퀘스트만 일치 할수 있게 지정할 수 있습니다.
spring:
  cloud:
    gateway:
      routes:
      - id: between_route
        uri: https://example.org
        predicates:
        - Between=2017-01-20T17:42:47.789-07:00[America/Denver], 2017-01-21T17:42:47.789-07:00[America/Denver]

 

5.4 cookie 라우트 조건자

cookie 라우트 조건자는 두가지 파라메터를 가집니다. name과 정규표현식입니다. 특정 쿠키값이 존재하는 리퀘스트만 일치 할 수 있게 지정할 수 있습니다.

spring:
  cloud:
    gateway:
      routes:
      - id: cookie_route
        uri: https://example.org
        predicates:
        - Cookie=chocolate, ch.p

 

5.5 header 라우트 연산자

header 라우트 연산자는 두가지 파라메터를 가집니다. header 값과 정규표현식입니다. 특정 헤더값이 존재하는 리퀘스트만 일치 할 수 있게 지정할 수 있습니다.

spring:
  cloud:
    gateway:
      routes:
      - id: header_route
        uri: https://example.org
        predicates:
        - Header=X-Request-Id, \d+
 

5.6 host 라우트 연산자

host 라우트 연산자는 리스트형태의 파라메터를 갖습니다. 콤마(.) 를 포함한 ant-sytle의 패턴으로 이루어져 있으며, host 헤더에 포함된 리퀘스트만 일치 할 수 있게 지정 할 수 있습니다.

spring:
  cloud:
    gateway:
      routes:
      - id: host_route
        uri: https://example.org
        predicates:
        - Host=**.somehost.org,**.anotherhost.org

 

5.7 Method 라우트 연산자

Method 라우트 연산자는 하나, 혹은 하나 이상의 파라메터를 갖는다. http method 를 파라메터로 지정 가능하며, 해당 값이 동일한 리퀘스트만 일치 할 수 있게 지정 할 수 있다.
spring:
  cloud:
    gateway:
      routes:
      - id: method_route
        uri: https://example.org
        predicates:
        - Method=GET,POST

 

5.8  Path 라우트 연산자

path 연산자는 리퀘스트에서 주어진 값과 일치하는 경로를 매칭하는 연산자이다. 두가지 유형의 파라메터를 사용할 수 있습니다. 

spring:
  cloud:
    gateway:
      routes:
      - id: path_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment},/blue/{segment}

matchTrailingSlash 가 true (default : true)  일때, /red/1, /red/1/, red/blue 일 경우 위 조건으로 모두 매칭 되지만 false 인 경우 , /red/1/ 은 (마지막에 / 가 있는경우) 는 매칭 되지 않는다. 

 

 

5.9 Query 라우트 연산자

 Query 연산자는 두개의 파라메터를 갖는다. 하나의 필수 파라메터가 입력되어야 하며, 정규표현식의 두번째 옵셔널한 파라메터가 입력 될수 있다.

spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=green
 
다음은 빨강과 green 을 매칭 하는 연산값이다.
spring:
  cloud:
    gateway:
      routes:
      - id: query_route
        uri: https://example.org
        predicates:
        - Query=red, gree.

 

 

5.10 RemoteAddr 라우트 연산자 

RemoteAddr 연산자는 CIDR 표기의 최소한 하나 이상의 IP를 입력 해야 한다. (192.168.0.1/16, IP/SUBNETMASK)

요청한 곳의 IP가 매칭되는 리퀘스트만 일치 할 수 있게 지정 할 수 있다.

spring:
  cloud:
    gateway:
      routes:
      - id: remoteaddr_route
        uri: https://example.org
        predicates:
        - RemoteAddr=192.168.1.1/24

상세참조(https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#modifying-the-way-remote-addresses-are-resolved)

 

 

5.11 Weight 라우트 연산자

Weight 연산자는 group과 weight , 두개의 파라메터를 갖는다.  이는 두 그룹별로 가중치를 가진다.

spring:
  cloud:
    gateway:
      routes:
      - id: weight_high
        uri: https://weighthigh.org
        predicates:
        - Weight=group1, 8
      - id: weight_low
        uri: https://weightlow.org
        predicates:
        - Weight=group1, 2
 

 

6. Gateway 필터 연산자

 Route 필터는 유입된 http 리퀘스트나 나가는 http 결과를 같은 수준에서 수정할 수 있게 해준다. route 필터는 특정 경로로 지정된다. Spring Cloud Gateway 는 많은 빌트인 GatewayFilter 팩토리를 제공한다.

6.1 AddRequestHeader Gateway 팩토리

AddRequestHeader Gateway 팩토리는 name 과 value 를 갖는다. 

 

Example 13. application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        filters:
        - AddRequestHeader=X-Request-red, blue

이 설정은 매칭된 모든 resuest 에 대해 X-Resuest-red:blue Header를 다운스트림 Header에 추가한다. 

 

AddRequestHeader는 경로나 호스트를 매칭할수 있는 지시자도 사용 가능하다. URI 변수는 값으로 사용될 수 있으며 런타임에도 확장된다. 다음은 AddRequestHeader를 구성하는 예제이다.

 

변수를 사용하는 헤더 GatewayFilter:

Example 14. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_header_route
        uri: https://example.org
        predicates:
        - Path=/red/{segment}
        filters:
        - AddRequestHeader=X-Request-Red, Blue-{segment}

 

6.2 AddRequestParameter Gateway 팩토리

AddRequestParameter Gateway 팩토리는 name 과 value 를 갖는다. 

 

Example 15. application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        filters:
        - AddRequestParameter=red, blue

이 설정은 매칭된 모든 다운스트림 request의 query string에 red=blue 가 추가될 것이다.

 

AddRequestParameter 는 경로나 호스트를 매칭할수 있는 지시자도 사용 가능하다. URI 변수는 값으로 사용될 수 있으며 런타임에도 확장된다. 다음은 AddRequestParameter 를 구성하는 예제이다.

Example 16. application.yml

spring:
  cloud:
    gateway:
      routes:
      - id: add_request_parameter_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddRequestParameter=foo, bar-{segment}

 

6.3 AddResponseHeader Gateway 팩토리

The AddResponseHeader GatewayFilter Factory takes a name and value parameter. The following example configures an AddResponseHeader GatewayFilter:

Example 17. application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        filters:
        - AddResponseHeader=X-Response-Red, Blue

This adds X-Response-Red:Blue header to the downstream response’s headers for all matching requests.

AddResponseHeader 는 경로나 호스트를 매칭할수 있는 지시자도 사용 가능하다. URI 변수는 값으로 사용될 수 있으며 런타임에도 확장된다. 다음은 AddResponseHeader 를 구성하는 예제이다.

Example 18. application.yml
spring:
  cloud:
    gateway:
      routes:
      - id: add_response_header_route
        uri: https://example.org
        predicates:
        - Host: {segment}.myhost.org
        filters:
        - AddResponseHeader=foo, bar-{segment}

 

 

 

 

 

 

 

 

(작성중입니다...)

 

 

 

 

 

참고 : https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

참고 : https://cheese10yun.github.io/spring-cloud-gateway/

 

반응형