Spring Cloud + MSA (2)

김준영·2023년 3월 4일
1

Spring Cloud + MSA

목록 보기
2/9

Spring Cloud Gateway - Filter


앞서 작성한 파일을 가지고 진행한다.

server:
  port: 8000

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

spring:
  application:
    name: api-gateway-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/**

application.yml 파일에 라우트 정보를 주석 처리 후 자바 코드로 필터를 적용해보자.

간단한 예제


api-gateway-service

package com.example.apigatewayservice.config;

import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
public class FilterConfig {
    @Bean
    public RouteLocator gatewayRoutes(RouteLocatorBuilder builder){

        return builder.routes()
                .route(r -> r.path("/first-service/**")
                        .filters(f -> f.addRequestHeader("first-request", "first-request-header")
                                .addResponseHeader("first-response", "first-response-header"))
                        .uri("http://localhost:8081"))
                .route(r -> r.path("/second-service/**")
                        .filters(f -> f.addRequestHeader("second-request", "second-request-header")
                                .addResponseHeader("second-response", "second-response-header"))
                        .uri("http://localhost:8082"))
                .build();

    }
}

위 코드는 위에서 주석처리한 것을 자바코드로 나타낸 것이다.

필터 설정파일을 하나 생성하고 RouteLocator 빈을 하나 등록한다.
매개변수로 RouteLocatorBuilder를 받고 빌드를 진행한다.

람다 식을 사용해서 r.path("")로 요청이 오면 uri("")으로 보내준다는 소리다. 그리고 가운데 필터를 하나 적용하는 것이다.

필터는 요청을 받으면 헤더에 first-request라는 key에 first-request-header라는 값을 추가한다. 마찬가지로 응답에도 추가하여 uri로 보낸다.

package com.example.firstservice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestHeader;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/first-service")
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";
    }
}

위 코드는 first-service controller 코드이다.

위 서비스에서 요청이 들어오고 @RequestHeader를 사용해서 gateway에서 추가한 요청 헤더를 받은 후 로그로 찍어본다.

그리고 응답으로 "Hello World in First Service"를 보낸다.

브라우저에서 확인하면 응답해더에 우리가 아까 추가한 헤더와 값이 들어가 있고,

First service에도 요청에 추가한 값이 들어가있다.

만약 프로퍼티 파일로 작성하고 싶을때는

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

        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**
          filters:
            - AddRequestHeader=second-request, second-request-header2
            - AddResponseHeader=second-response, second-response-header2

이렇게 추가해주면 작동한다.

간단한 예제를 통해 Filter를 추가해보았다.

profile
ㅎㅎ

0개의 댓글