1 분 소요

Global Filter도 이전 글에서 만든 Custom Filter와 비슷한 방식으로 만들 수 있다. (apply() 메서드 지정)
하지만 Global Filter는 “공통” 필터라는 점에서 Custom Filter와 차이가 있다.
Custom Filter는 아래와 같이 라우팅 정보마다, 필요한 필터가 있을 경우에는 지정해주어야 했다.

spring:
  application:
    name: apigateway-service
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first-service/**
          filters:
            - CustomFilter  # 🌟 CustomFilter 등록
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**
          filters:
            - CustomFilter  # 🌟 CustomFilter 등록

하지만, 공통적인 필터가 있다고 하면 매번 이렇게 지정하는 것이 아니라
Global Filter를 통해 한번에 처리할 수 있다.

코드

apigateway-service

filter/GlobalFilter.java

이 전에 만든 CustomFilter와 같은 위치에 GlobalFilter를 생성한다.

@Component
@Slf4j
public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.Config> {

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

    @Override
    public GatewayFilter apply(Config config) {
        return ((exchange, chain) -> {
            ServerHttpRequest request = exchange.getRequest();
            ServerHttpResponse response = exchange.getResponse();

            log.info("Global Filter baseMessage: {}", config.getBaseMessage());

            if (config.getPreLogger()) {
                log.info("Global Filter Start: request id -> {}", request.getId());
            }

            return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    if (config.getPostLogger()) {
                        log.info("Global Filter End: response id -> {}", response.getStatusCode());
                    }
                }));
        });
    }

    @Data
    public static class Config {
        // configuration 정보를 넣기
        private String baseMessage;
        private Boolean preLogger;
        private Boolean postLogger;
    }
}

application.yml

...
spring:
  application:
    name: apigateway-service
  cloud:
    gateway:
      default-filters: # 🌟 GlobalFilter 추가
        - name: GlobalFilter
          args:
            baseMessage: Spring Cloud Gateway Global Filter
            preLogger: true
            postLogger: true
      routes:
        - id: first-service
          uri: http://localhost:8081/ 
          predicates:
            - Path=/first-service/** 
          filters:
            - CustomFilter 
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**
          filters:
            - CustomFilter

이번에는 first-servicesecond-service는 건들지 않는다.

포스트맨 결과

포스트맨을 통해 http://localhost:8000/first-service/check에 접속해보자.
apigateway-service의 콘솔에 아래와 같은 로그가 찍힌다.
스크린샷 2022-09-28 오전 12 52 35
위 사진을 보면 Global Filter StartGlobal Filter End 사이에,
Custom Pre FilterCustom Post Filter가 실행 되었음을 알 수 있다.

커스텀 필터는 각각의 라우터 정보마다 추가해 주어야 하는 필터이고,
커스텀 필터가 실행되기 전에 글로벌 필터가 실행된다.

이번에는, 이어서 http://localhost:8000/second-service/check에 접속해보자. 스크린샷 2022-09-28 오전 12 46 09



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기