Custom Filter

duckbill413·2024년 7월 30일
0

Spring Cloud

목록 보기
3/10
post-thumbnail
  • AbstractGatewayFilterFactory를 상속받아 Custom Filter를 구현할 수 있다.
  • Gateway의 Custom Filter를 이용하여 JWT 토큰을 인증 작업을 체크하는 작업등의 작업을 할 수 있다.

CustomFilter 생성 실습

  1. Gateway Project 에 CustomFilter class 구현

    @Slf4j
    @Component
    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 code -> {}", response.getStatusCode());
                }));
            };
        }
    
        public static class Config {
            // Put the configuration properties
        }
    }
    • AbstractGatewayFilterFactory를 상속하여 Custom Filter 구현
    • CustomFilter.Config는 Custom Filter의 Configuration 정보 class
    • apply method를 오버 로딩 한뒤 filter 를 구현
    • PRE, POST 필터의 구현 방식 확인
  2. application.yml의 gateway filters 에 CustomFilter 등록

    spring:
      application:
        name: api-gateway-service
      cloud:
        gateway:
          routes:
            - id: first-service
              uri: http://localhost:8081/
              predicates:
                - Path=/first-service/**
              filters:
                - AddRequestHeader=first-request, first-request-header2
                - AddResponseHeader=first-response, first-response-header2
                - CustomFilter # 추가
            - id: second-service
              uri: http://localhost:8082/
              predicates:
                - Path=/second-service/**
              filters:
                - AddRequestHeader=second-request, second-request-header2
                - AddResponseHeader=second-response, second-response-header2
                - CustomFilter # 추가
  3. Service Project에 Test를 위한 API 생성

    First-Service, Second-Service의 Controller에 다음과 같은 API를 추가

    @GetMapping("/check")
    public String check() {
        return "Hi, there. This is a message from Second Service";
    }
  4. Custom Filter 작동 테스트

    http://localhost:8000/first-service/check

    w.duckbill.gateway.filter.CustomFilter   : Custom PRE filter: request id -> 994c106b-5
    w.duckbill.gateway.filter.CustomFilter   : Custom POST filter: response code -> 200 OK
    • 로그를 확인해 보면 PRE, POST Filter가 작동됨이 확인 가능
profile
같이 공부합시다~

0개의 댓글

Powered by GraphCDN, the GraphQL CDN