Sun's Blog

Spring Cloud Gateway 본문

ETC

Spring Cloud Gateway

버스는그만 2023. 8. 13. 22:17

Spring Cloud에는 Gateway말고 Zuul도 있다. 둘의 큰 차이점은 비동기 지원의 유무이며 Gateway는 비동기를 지원하고 있다.

의존성 추가

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

 

API Gateway

요청 url에 맞게 API 프록시 역할을 한다. 아래의 두 방식 중에 적절한 방식을 이용하면 된다.(XML은 ㅁ?ㄹ)

YAML 방식

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first/**
        - id: second-service
          uri: http://localhost:9002/
          predicates:
            - Path=/second/**

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false
    service-url:
      defaultZone: http://127.0.0.1:8761/eureka

Java Config(방식)

@Configuration
public class FilterConfig {
    @Bean
    RouteLocator gatewayRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path("/first/**")
                        .uri("http://localhost:8081"))
                .route(r -> r.path("/second/**")
                        .uri("http://localhost:9002"))
                .build();
    }
}

Java를 보면 GateWay에 Filter를 만들 수 있다. 아래의 코드는 커스텀 필터를 만드는 방법이다.

CustomFilter

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

    @Override
    public GatewayFilter apply(Config config) {
        return ((exchange, chain) -> {
        });
    }

    public static class Config {

    }
}
  • GATEWAY에서 커스텀 필터를 만들려면 AbstractGatewayFilterFactory를 상속받아야 하며 Config 클래스를 따로 만들어야 한다.
  • Config 클래스는 뒤에 나올 GlobalFilter에서 다뤄질 예정이다.
  • exchange에는 요청에 대한 정보가 있으며 MONO는 0~1개의 결과를 처리하는 Reactor의 객체이다.

일단 GateWay는 WebFlux를 기반으로 만들어졌으며 WAS 또한 비동기에 적합한 Netty로 만들어 졌다. 이를 완전히 이해하기 위해서는 먼저 WebFlux를 공부하는 것이 좋을 것 같으므로 추후 공부가 필요할 것 같다.

CustomFilter 등록

spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first/**
          filters:
            - CustomFilter
        - id: second-service
          uri: http://localhost:9002/
          predicates:
            - Path=/second/**
          filters:
            - CustomFilter

위와 같이 원하는 경로에 적절한 필터를 등록 할 수 있다.

GlobalFilter

커스텀 필터는 각각의 경로마다 등록해줘야 한다면 글로벌 필터는 모든 경로에서 공통적으로 적용되는 필터다. 순서는 아래와 같다.

  1. 글로벌 필터 Request
  2. 커스텀 필터: Request
  3. 커스텀 필터: Response
  4. 글로벌 필터: Response
@Slf4j
@Component
public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.GlobalConfig> {

    public GlobalFilter() {
        super(GlobalConfig.class);
    }
    @Override
    public GatewayFilter apply(GlobalConfig config) {
        log.info("Global Filter: Request: " + config.baseMessage);
        return ((exchange, chain) -> chain.filter(exchange).then(Mono.fromRunnable(() -> {
            log.info("Global Filter: Response: " + config.baseMessage);
        }
        )));
    }

    @Data
    public static class GlobalConfig {
        private String baseMessage;
    }
}
spring:
  application:
    name: gateway-service
  cloud:
    gateway:
      default-filters:
        - name: GlobalFilter
          args:
            baseMessage: This is Base Message
  • default-filter로 글로벌 필터를 적용시킨다.
  • config의 field 값들은 args로 초기화 할 수 있다.

실행

'ETC' 카테고리의 다른 글

Accept와 Content-Type  (0) 2023.08.15
팝업, 모달 그리고 토스트 메시지  (0) 2023.08.14
Spring Cloud Eureka  (0) 2023.08.13
Microservice와 Spring Cloud 소개  (0) 2023.08.12
Java - Record  (0) 2023.08.09