Spring Cloud - 5. Spring Cloud Gateway Global Filter 적용

Spring Cloud로 개발하는 마이크로서비스 애플리케이션 5 - Spring Cloud Gateway Global Filter 적용

공통적으로 실행될 수 있는 Filter. 라우팅 정보마다 개별적으로 필터를 지정해야 하는 Custom Filter와 다르게 Global Filter의 경우 한번에 처리를 할 수 있다.

GlobalFilter.java

@Component
@Slf4j
public class GlobalFilter extends AbstractGatewayFilterFactory<GlobalFilter.Config> {
public GlobalFilter(){
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("Global Filter baseMessage : {}", request.getId());

if(config.isPreLogger()){
log.info("Global Filter Start: request id -> {}", request.getId());
}
// Custom Post Filter
return chain.filter(exchange).then(Mono.fromRunnable(() -> {
if(config.isPostLogger()){
log.info("Global Filter End: response code -> {}", response.getStatusCode());
}
}));
};
}

@Data
public static class Config{
// Put the configuration properties
private String baseMessage;
private boolean preLogger;
private boolean postLogger;
}
}

application.yml

spring:
application:
name: apigateway-service
cloud:
gateway:
default-filters:
- name: GlobalFilter
args:
baseMessage: Spring Cloud Gateway GlobalFilter
preLogger: true
postLogger: true
Share