본문 바로가기

MSA (MicroServiceArchitecture)/Eureka & Spring Cloud Gateway

MSA Spring (CustomFilter)

1. application.yml 파일을 아래와 같이 수정합니다.

기존에 설정된 필터 정보에서 Add 부분을 주석처리하고 CustomFilter를 추가해 줍니다.

server:
  port: 8000

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/ #http://127.0.0.1:8081/first-service/welcome #이동될 주소
          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/ #http://127.0.0.1:8082/second-service/welcome #이동될 주소
          predicates:
            - Path=/second-service/** #사용자가 입력한 조건값
          filters:
#            - AddRequestHeader=second-request, second-request-header2 #앞에값이 키값이고 뒤에값이 벨류이다.
#            - AddResponseHeader=second-response, second-response-header2 #앞에값이 키값이고 뒤에값이 벨류이다.
             - CustomFilter # 해당 내용 추가

- FirstServiceConroller와 SecondServieController에 아래의 코드를 추가해 줍니다.

    @GetMapping("/check")
    public String check() {
        return "Hi, there. This is a message from First Service";
    }

2. filter 패키지와 그리고 필터 패키지안에 CustomFilter 클래스를 생성합니다.

3. 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) {
        // 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
    }
}

- 다음시간에는 글로벌 필터에 대해서 알아보자.