Spring Cloud - 4. Spring Cloud Gateway Custom Filter 적용

사용자 정의 필터 만들기

AbstractGatewayFilterFactory 를 이용해 Custom 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: request id -> {}", response.getStatusCode());
}));
};
}

public static class Config{
// Put the configuration properties
}
}

설정에 추가하기

  • spring.cloud.gateway.routes.filters

application.yml

server:
port: 8080

eureka:
client:
register-with-eureka: false
fetch-registry: false
service-url:
defaultZone: http://localhost:8761/eureka

spring:
application:
name: apigateway-service
cloud:
gateway:
routes:
- id: first-service
uri: http://localhost:8081/
predicates:
- Path=/first-service/**
filters:
- CustomFilter
# - AddRequestHeader=first-request, first-request-header2
# - AddResponseHeader=first-response, first-response-header2
- id: second-service
uri: http://localhost:8082/
predicates:
- Path=/second-service/**
filters:
- CustomFilter
# - AddRequestHeader=second-request, second-request-header2
# - AddResponseHeader=second-response, second-response-header2
Share