Spring Cloud Gateway - Global Filter

sidohigar·2021년 10월 19일
0

Spring Boot

목록 보기
5/7
  1. GlobalFilter.java 생성
import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import lombok.Data;
import lombok.extern.slf4j.Slf4j;
import reactor.core.publisher.Mono;

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

    @Data
    public static class Config {
        private String baseMessage;
        private boolean preLogger;
        private boolean postLogger;
    }

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

            log.info("Global filter base message -> {}", config.baseMessage);

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

            // Global Post Filter
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                if(config.postLogger)
                    log.info("Global POST Filter: response code -> {}", response.getStatusCode());
            }));
        };
    }
}

  1. 설정파일 추가 (default-filters)
spring:
    application:
        name: apigateway-service
    cloud:
        gateway:
            default-filters:
                -   name: GlobalFilter
                    args:
                        baseMessage: Spring Cloud Gateway Global filter
                        preLogger: true
                        postLogger: true
            routes:
                -   id: tax-invoice
                    uri: http://tax.blueport.co.kr:8443/
                    predicates:
                        - Path=/v1/**
                    filters:
                        # - AddRequestHeader=headerName, headerValue
                        # - AddResponseHeader=headerName2, headerValue2
                        - CustomFilter

  1. 실행결과

GlobalFilter(PRE) -> CustomFilter(PRE) -> CustomFilter(POST) -> GlobalFilter(POST)

0개의 댓글