[MSA] Spring Cloud Gateway (3) - Custom Filter

2022. 7. 15. 15:39Software Architecture/MSA

반응형

++) 해당 포스팅은 이전 과정에서 진행했던 프로젝트를 사용하므로 이전 포스팅을 참고해야 합니다!

 

https://born2bedeveloper.tistory.com/56

 

[MSA] Spring Cloud Gateway (2) - Filter

이전 포스팅 참고 API Gateway는 클라이언트와 서비스 사이의 통신을 담당하며 단일 진입점을 통해 일괄적으로 요청을 처리할 수 있다. Spring Cloud Gateway는 현재 스프링 클라우드에서 제시한 API Gatewa

born2bedeveloper.tistory.com

 

저번 포스팅에서 언급했던 대로 이번에는 사용자 정의 필터를 만들어 볼 예정이다.

 

 CustomFilter 생성

 

기존 apigateway 프로젝트에 filter패키지를 추가하고 그 안에 CustomFilter 클래스를 아래와 같이 생성하자.

 

package com.example.apigatewayservice.filter;

import lombok.extern.slf4j.Slf4j;
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 reactor.core.publisher.Mono;

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

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

    @Override
    public GatewayFilter apply(Config config) {
        // Coustom 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 id -> {}", response.getStatusCode());
            }));
        };
    }
// Mono : 이 객체는 웹 플럭스라고 해서 spring 5에서 추가된 기능, 비동기 방식의 서버 지원 (단일값으로)
    public static class Config{
        // Put the configuration properties
    }
}

그 후 설정파일에 우리가 만든 filter를 등록해야한다.

 

 Custom Filter 등록

 

++) CustimFilter과 - 사이에 스페이스 한 칸을 띄워야 함! (오타 주의)

 

이전에 설정한 필터는 주석처리하고, 내가 만든 CustomFilter를 등록하자.

 

그 다음 first, second 서비스에 customfilter를 통해 반환시켜줄 메소드를 새로 만들자!

 

각각의 컨트롤러에 추가해주자.

 

 POSTMAN을 통한 확인

 

이제 우리가 설정해둔 컨트롤러를 호출해보도록 하자!

 

 

CustomFilter가 잘 적용된 것을 알 수 있다. 또한 PreCustomFilter와 PostCustomFilter에 추가한 log 출력 정보도 확인할 수 있다.

 

필자가 설정해둔 로그가 제대로 출력되고 있음을 확인할 수 있다!

second-service도 확인해보자

 

 

이렇듯 우리가 직접 CustomFilter를 등록하여 사전에 할 작업, 사후에 할 작업 (pre, post filter)에 대해 직접 정의내릴 수 있었다.

구현할 때에는 AbstractGatewayFilterFactory를 상속받아야 하고,  구현할 메소드는 apply이며 안에 pre 및 post filter를 정의해주면 된다. 지금은 간단한 출력 문장만 넣어놨지만 이후 로그인 관련 서비스를 구현할 때, 사용자 로그인을 이 필터에서 추가할 수 있다.

 

Filter의 종류는 Global , Logging등 다양하다.

https://cloud.spring.io/spring-cloud-gateway/reference/html/#global-filters

 

Spring Cloud Gateway

This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 5, Spring Boot 2 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them

cloud.spring.io

공식문서에도 자세히 나와있으니 따로 포스팅을 작성하진 않겠다.

기회가 된다면 여러분들은 따로 다뤄보는 것을 추천하겠다!

 

 

[참고 레퍼런스]

 

https://www.inflearn.com/course/%EC%8A%A4%ED%94%84%EB%A7%81-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%EB%A7%88%EC%9D%B4%ED%81%AC%EB%A1%9C%EC%84%9C%EB%B9%84%EC%8A%A4

 

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) - 인프런 | 강의

Spring framework의 Spring Cloud 제품군을 이용하여 마이크로서비스 애플리케이션을 개발해 보는 과정입니다. Cloud Native Application으로써의 Spring Cloud를 어떻게 사용하는지, 구성을 어떻게 하는지에 대해

www.inflearn.com