Spring Cloud Gateway (1) 설정

ljft183·2022년 12월 12일
0

Spring_Cloud_Gateway

목록 보기
1/3

기본 구성에 custom filter 하나만 추가해둔 예시

application.yml 설정

참조 : https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/

server:
  port: 8080

spring:
  application:
    name: gateway
  cloud:
    gateway:
      routes:
        - id: rest
          uri: http://localhost:8081
          predicates: # Custom filter
            - Path=/rest/**, /api/**                 # 여러 경로 양식 작성시 , 로 구분
          filters:
            - ApiLogFilter
        - id: web
          uri: http://localhost:8082
          predicates:
            - Path=/web/**, /web
          filters: # 기본 제공 필터
            - SetRequestHostHeader=localhost:8080    # web-app redirect 시 header host 변경 방지용 

ApiLogFilter

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

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

            log.info("api-call");
			if (config.isPreLogger()) {
                log.info("[Filter Start] request ID: {}, method: {}, path: {}", request.getId(), request.getMethod(), request.getPath());
            }
            
            // Post Filter
            return chain.filter(exchange).then(Mono.fromRunnable(() -> {
                if (config.isPostLogger()) {
                    log.info("[Filter End  ] request ID: {}, method: {}, path: {}, statusCode: {}", request.getId(), request.getMethod(), request.getPath(), response.getStatusCode());
                }
            }));
        });
    }
    
    @Data
    public static class Config {
        // put the configure
        private String baseMessage;
        private boolean preLogger;
        private boolean postLogger;
    }
}

0개의 댓글