API Gateway Service - 1

2025. 1. 26. 09:00·MSA 공부

 

1. Spring Cloud Gateway

Dependency

application.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:
      mvc:
        routes: # gateway로써 라우팅 방향 정보 등록
          - id: first-service
            uri: <http://localhost:8081>
            predicates:
              - Path=/first-service/**
          - id: second-service
            uri: <http://localhost:8082/>
            predicates:
              - Path=/second-service/**

라우팅 방식

위와 같은 application.yml 설정이면 다음과 같은 방식으로 동작한다.

  • http://localhost:8000/frist-service/welcome —> http://localhost:8081/frist-service/welcome
  • 즉, /frist-service/welcome 이 부분이 그대로 뒤로 붙여진다.

실행 결과

 


2. Spring Cloud GateWay - Filter

사전 작업

application.yml 주석 처리

라우팅을 Filter에서 조작하기 위해 application.yml routes부분을 주석처리

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

build.gradle수정

gateway-mvc를 주석처리 후 새 의존성 추가

//implementation 'org.springframework.cloud:spring-cloud-starter-gateway-mvc'
implementation 'org.springframework.cloud:spring-cloud-starter-gateway'

FilterConfig

초기 상태

.route() 여기에 실제 라우팅 정보를 작성한다 (자바코드로 작성 가능)

@Configuration
public class FilterConfig {

    @Bean
    public RouteLocator gatewatRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route() // 실제 라우팅 정보를 람다식으로 작성
                .build();
    }
}

기본 틀

r.path에는 어느 경로로 들어왔을 때 동작할 지

.uri는 어느 경로로 라우팅 할 지 정의한다.

.filters는 해당 경로에 request를 key-value로 붙여서 정의된 라우팅 주소로 보내고 다시 돌아오는 응답값에 추가 response를 key-value로 붙여서 클라이언트에게 반환한다.

즉 apigateway를 통과할 때 request와 response를 삽입한다.

    @Bean
    public RouteLocator gatewatRoutes(RouteLocatorBuilder builder) {
        return builder.routes()
                .route(r -> r.path() // 이 경로로 들어오면
                        .filters()   
                        .uri())      // 이 경로로 라우팅한다.
                .build();
    }

실제 사용 예시는 다음과 같다.

    @Bean
    public RouteLocator gatewatRoutes(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>"))
                .build();
    }

이제 second-service에 관한 라우팅도 추가하면 최종 결과는 다음과 같다.

  @Bean
  public RouteLocator gatewatRoutes(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();
  }

동작 확인하기

request 확인

다음 코드를 추가해서 first-service 컨트롤러로 들어오는 요청에 대해서 first-request라는 헤더가 있는 지 확인 후 출력

    @GetMapping("/message")
    public String message(@RequestHeader("first-request") String header ){

        log.info(header);
        return "Hello World in First Service. ";
    }

response 확인

개발자 도구 연 다음

Network → message 클릭 → Headers → Response Headers 클릭 시 Response 확인 가능

 


3. Spring Cloud Gateway - Filter 2 (다른 방법)

application.yml 에서 Filter 추가하기

Bean 등록 후 자바 코드로 Filter를 조작하는 방법 대신

application.yml에서도 각 라우팅 정보에 대해 Filter를 정의할 수 있다.

다음 yaml은 spring-cloud-starter-gateway 의존성 기준으로 작성됐다. (-mvc가 아님)

implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
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-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

#      mvc:
#        routes:
#          - id: first-service
#            uri: <http://localhost:8081>
#            predicates:
#              - Path=/first-service/**
#          - id: second-service
#            uri: <http://localhost:8082/>
#            predicates:
#              - Path=/second-service/**

 

'MSA 공부' 카테고리의 다른 글

FeignClient 사용 및 예외 처리  (0) 2025.05.21
Custom Filter, GlobalFilter 적용  (0) 2025.02.26
Service Discovery  (1) 2025.01.26
'MSA 공부' 카테고리의 다른 글
  • FeignClient 사용 및 예외 처리
  • Custom Filter, GlobalFilter 적용
  • Service Discovery
koreaioi
koreaioi
  • koreaioi
    koreaioi
    koreaioi
  • 글쓰기 관리
  • 전체
    오늘
    어제
    • 분류 전체보기 (157)
      • JAVA (2)
      • 알고리즘 (88)
        • 백준 (11)
        • String(문자열) (12)
        • Array(1, 2차원 배열) (13)
        • Two pointers, Sliding windo.. (6)
        • HashMap, TreeSet(해쉬, 정렬지원 S.. (5)
        • Stack, Queue(자료구조) (8)
        • Sorting and Searching(정렬, 이.. (10)
        • Recursive, Tree, Graph(DFS,.. (14)
        • DFS, BFS 활용 (6)
        • 다시 시작! (1)
        • 기초 수학 (1)
      • 일상 (22)
      • Github (1)
      • MSA 공부 (4)
      • 경제, 금융, 디지털, 시사 (3)
      • 라즈베리파이 (10)
      • 프로젝트에서 일어난 일 (15)
      • FrontEnd 공부 (9)
        • React (8)
      • Spring (2)
      • 기술 세미나 (1)
  • 블로그 메뉴

    • 홈
    • 태그
    • 방명록
  • 링크

  • 공지사항

  • 인기 글

  • 태그

  • 최근 댓글

  • hELLO· Designed By정상우.v4.10.3
koreaioi
API Gateway Service - 1
상단으로

티스토리툴바