1 분 소요

Custom Filter는 사용자 정의 필터로
로그를 출력하거나, 인증을 처리하거나, 로케일을 바꿀 수 있다.

이번에는 직접 Custom Filter를 정의해 등록해보자.

코드

apigateway-service

filter/CustomFilter.java

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

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

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

            log.info("Custom Pre Filter: request id -> {}", request.getId());

            // 🌟 Custom Post Filter
            return chain.filter(exchange)
                .then(Mono.fromRunnable(() -> {
                    log.info("Custom Post Filter: response status code -> {}", response.getStatusCode());
                }));
        });
    }

    public static class Config {
        // configuration 정보를 넣기
    }
}

application.yml

...
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 적용

first-service

FirstServiceController.java

@RestController
@RequestMapping("/first-service")
@Slf4j
public class FirstServiceController {
    ...
    @GetMapping("/check")
    public String check() {
        return "Check First Service";
    }
}

second-service

SecondServiceController.java

@RestController
@RequestMapping("/second-service")
@Slf4j
public class SecondServiceController {
    ...
    @GetMapping("/check")
    public String check() {
        return "Check Second Service";
    }
}

포스트맨 테스트 결과

포스트맨을 통해 http://localhost:8000/first-service/checkhttp://localhost:8000/second-service/check에 접속하면,
apigateway-service의 콘솔에 아래와 같은 로그가 찍힌다.
스크린샷 2022-09-27 오후 11 13 13



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

맨 위로 이동하기