AbstractGatewayFilterFactory
를 상속받아 Custom Filter를 구현할 수 있다.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 정보 classapply
method를 오버 로딩 한뒤 filter 를 구현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 # 추가
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";
}
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