MakerHyeon

[springCloud] Spring Cloud Gateway filter 적용 본문

SpringBoot/SpringCloud

[springCloud] Spring Cloud Gateway filter 적용

유쾌한고등어 2023. 4. 7. 14:32

 

yml 설정을 java클래스에서 코드 설정으로 옮겨보자!

springCloudGateway안에서 이를 처리해볼 것이다.

이번 실습에서는 requestheader는 client요청이들어오면 request handler에서 header를 추가한다.

마찬가지로 client요청이 나갈때 responseheader를 추가해 내보내보자.


- gateway project의 yml설정(이전에만든 yml 주석처리)

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/
#          predicates:
#            - Path=/first-service/**
#        - id: second-service
#          uri: http://localhost:8082/
#          predicates:
#            - Path=/second-service/**

 

- FilterConfig.class 생성 (gateway java 코드)

- 아래 코드를 정리하면, 사용자의 path요청이들어오면 헤더를 추가후 uri로 이동한다.
- 클라이언트 요청이 오는것을 중간에 가로채서 추가적 response를 넣어서 응답하는 코드이다.

@Configuration //스프링부트가 처음 부트스트랩위에서 작동시작할때 메모리에 먼저등록한다.
public class FilterConfig {
    @Bean
    public RouteLocator gatewatRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
        .route(r->r.path("/first-service/**") // path 확인
                .filters(f -> f.addRequestHeader("first-request","first-request-header") //key,value형태로 저장
                        .addResponseHeader("first-response","first-response-header")) // 필터 적용
                .uri("http://localhost:8081")) // uri로 이동

                .build();
    }
}

 

- first-service project의 컨트롤러에서 message받을 맵핑을 추가로 생성해준다.

- 헤더 확인을 위해 log를 남겨보자.

// http://localhost:8081/first-service/welcome
@RestController
@RequestMapping("/first-service/")
@Slf4j
public class FirstServiceController {
    @GetMapping("/welcome")
    public String welcome(){
        return "Welcome to the First service.";
    }

    @GetMapping("/message")
    public String message(@RequestHeader("first-request") String header){
        log.info(header);
        return "Hello World in First Service.";
    }
}

 

제대로 헤더 결과값을 받아오는 것을 확인할 수 있다!

<실행 결과>

 


이제 yml에서 필터를 적용해보자.

 

먼저 위 FilterConfig.class에서 @Configuration,@Bean을 주석처리해준다.

이러면 스프링부트의 동작하에 해당코드는 적용되지않는다.

 

- gateway 프로젝트의 yml에서 새롭게 추가된부분 filters를 보자!

- 각 헤더, value키를 입력해준다.

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/
          predicates:
            - Path=/first-service/**
          filters:
            - AddRequestHeader=first-request, first-requests-header2
            - AddResponseHeader=first-response, first-response-Header2
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**

 

- 이제 서버를 실행하고, http://localhost:8000/first-service/message로 접속해보자.

- 코드 실행 결과 아래와 같이 value값이 잘 뜨는것을 볼 수 있다.

<실행 결과 화면>

 

개발자도구->네트웍에서 응답 헤더(first-response-Header2) 또한 잘 받아온 것을 볼 수 있다!

 

 

Comments