코딩공부/MSA

[Spring Cloud] Spring Cloud Gateway - 설정 및 동작 원리

내일의기대 2024. 9. 2. 22:32

본 글에서는 Spring Cloud의 핵심 프로젝트 중 하나인 Spring Cloud Gateway에 대해서 공식 홈페이지 홈페이지에 있는 기본내용의 일부를 번역 및 정리한 글입니다. 이번글에서는 Spring Cloud Gateway의 두 가지 형태, 용어, 기본 설정, 동작 원리에 대해서 파악하실 수 있습니다.

Spring Cloud Gatway의 두 가지 형태

Spring Cloud Gateay는 보안, 모니터링 및 metrics, resiliency를 제공하는 단순하지만 효율적인 API 라우팅 기능을 제공합니다.
Spring Cloud Gateway는 Server와 Proxy Exchagne라는 두 가지 형태를 제공합니다.

  • Server 형태는 Spring Boot 어플리케이션안에서 기능을 모두 갖춘 API gateway로 단독 혹은 embeded 되어 구동됩니다.
  • Proxy Exchange 형태는 WebFlux 혹은 MVC 어플리케이션의 annotation 형태로 구동되며 ProxyExchange 라는 특별한 객체 사용을 허용하여 web handler method의 파라메터로 사용할 수 있게 합니다.

Server 형태는 우리가 일반적으로 아는 Spring Cloud Gateway를 말하고 Proxy Exchange는 다음과 같이 method parameter의 형태로 주입 받아서 사용할 수 있는것으로 보이나 실제 사용은 해보지 않았습니다.

@RestController
@SpringBootApplication
public class GatewaySampleApplication {

    @Value("${remote.home}")
    private URI home;

    @GetMapping("/test")
    public ResponseEntity<?> proxy(ProxyExchange<byte[]> proxy) throws Exception {
        return proxy.uri(home.toString() + "/image/png").get();
    }

}

용어 사전 및 설정 예시

  • Route : gateway의 기본 구성 요소입니다. ID, 목적지 URI, predicate의 집합, filters의 집합으로 구성됩니다.
  • Predicate : Java 8 Function Predicate입니다. 입력 타입은 Spring Framework의 ServerWebExchange 입니다. 이를 통해 headers나 parameters와 같은 HTTP reqeust의 어떤것이라도 매칭될 수 있습니다.
  • Filter : 이것은 GatewayFilter의 한 종류로 특정 factory로 만들어집니다. 참고로 Spring Cloud Gataway는 다양한 built-in factory들을 제공합니다. Filter를 통해서 request나 response 요청을 흘려보내기 전후로 수정할 수 있게 합니다.

아래는 gateway 설정을 하는 application.yml 파일의 예시입니다.

spring:
  cloud:
    gateway:
      routes:
      - id: ingredients
        uri: lb://ingredients
        predicates:
        - Path=/ingredients/**
        filters:
        - name: CircuitBreaker
          args:
            name: fetchIngredients
            fallbackUri: forward:/fallback
      - id: ingredients-fallback
        uri: http://localhost:9994
        predicates:
        - Path=/fallback
        filters:
        - name: FallbackHeaders
          args:
            executionExceptionTypeHeaderName: Test-Header

각 route에 대한 설정은 spring.cloud.gateway.routes로 시작되고 id, uri, predicates, filters가 포함됩니다. 예를들어 위의 ingredients라는 route의 경우 Path라는 Route Predicate Factory를 사용하고 CircuitBreaker라는 Filter Factory를 사용합니다. 위의 예시에서 predeicate는 shorcut configuration 형태를 사용했고 filters는 fully exapnded argument 형태를 사용했는데요 다음 예시를 보면 차이를 더 확실 히 알 수 있습니다.

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

shortcut 설정은 [filter 이름]=argument1,argument2 형태로 구성되고 fully expanded argument 설정은 name과 args를 명시적으로 적어줍니다.

동작 원리

위 그림과 같이 우선 Client는 Spring Cloud Gateway로 요청을 만들어 보냅니다. Gateay Handler Mapping이 요청이 route에 매치되는 것을 확인하면 Gateway Web Handler로 요청을 보냅니다. 이 Handler는 요청에 맞는 filter chain을 실행합니다. 위 그림에서 pre / post로 점선으로 나뉘어져 있는 이유는 proxy 요청이 보내지기 전후에 filter가 실행 될 수 있기 때문입니다. pre filter의 경우 proxy 요청이 만들어지기 전에 실행되고, post filter는 proxy가 실행되고 난 다음 실행됩니다.