Spring Cloud Gateway Routing 설정

song·2025년 3월 23일
0

SpringCloud

목록 보기
9/13

마이크로 서버 준비

Routing 전략

  • 많은 방법이 있음
  • Path 기반 routing 사용
  • 시간 기반 routing . . 등이 있음

application.properties를 통한 라우팅 설정

  • Spring Cloud Gateway 프로젝트에서 추가
  • Path 방식
  • 특정 패턴이 오면, 특정 서버로 라우팅
# Routing 전략
spring.cloud.gateway.routes[0].id=ms1
spring.cloud.gateway.routes[0].predicates[0].name=Path
spring.cloud.gateway.routes[0].predicates[0].args.pattern=/ms1/**
spring.cloud.gateway.routes[0].uri=http://localhost:8081

spring.cloud.gateway.routes[1].id=ms2
spring.cloud.gateway.routes[1].predicates[0].name=Path
spring.cloud.gateway.routes[1].predicates[0].args.pattern=/ms2/**
spring.cloud.gateway.routes[1].uri=http://localhost:8082

application.yml 를 통한 라우팅 설정

server:
  port: 8080

spring:
  cloud:
    gateway:
      routes:
        - id: ms1
          uri: http://localhost:8081
          predicates:
            - Path=/ms1/**
        - id: ms2
          uri: http://localhost:8082
          predicates:
            - Path=/ms2/**

Config 클래스를 통한 라우팅 설정

  • config > CustomRoute.java 생성
@Configuration
public class CustomRoute {

    @Bean
    public RouteLocator cRouter(RouteLocatorBuilder builder){

        return builder.routes()
                .route("ms1", r -> r.path("/ms1/**")
                        .uri("http://localhost:8081"))
                .route("ms2", r -> r.path("/ms2/**")
                        .uri("http://localhost:8082"))
                .build();
    }
}

dependencies

dependencies {
	implementation 'org.springframework.boot:spring-boot-starter-webflux'
	implementation 'org.springframework.cloud:spring-cloud-starter-gateway'
    implementation 'org.springframework.cloud:spring-cloud-starter-netflix-eureka-client'
}

주의사항

  • dependencies에 아래 의존성이 있을 경우, 오류
implementation 'org.springframework.cloud:spring-cloud-starter-gateway-mvc'
  • spring-cloud-starter-gateway-mvc는 내부적으로 spring-boot-starter-web을 자동으로 끌어오기 때문에, WebFlux 기반 Gateway 프로젝트와 충돌이 발생함
  • spring-cloud-starter-gateway: WebFlux 기반의 비동기, 논블로킹 Gateway
  • spring-cloud-starter-gateway-mvc: Servlet(MVC) 기반 Gateway. 주로 spring-boot-starter-web과 같이 씀.
  • 둘은 완전히 다른 방식으로 동작하고, 동시에 사용하면 충돌이 남

WebFlux 기반 Gateway vs Servlet(MVC) 기반 Gateway

WebFlux 기반 Gateway (spring-cloud-starter-gateway)

  • 논블로킹
  • 고성능 트래픽 처리 필요할 때 (ex. 1만 동시접속 이상)
  • 마이크로서비스 환경에서 라우팅/보안 필터 기능 수행할 때
  • 실시간 스트리밍 또는 SSE/WebSocket 필요할 때
  • 서버 리소스가 제한적일 때
  • ex) 실시간 알림 서버, IoT 대량 요청 처리, 대규모 API Gateway

Servlet(MVC) 기반 Gateway (spring-cloud-starter-gateway-mvc)

  • 블로킹
  • 기존 프로젝트라 Spring MVC 기반일 때
  • 복잡한 필터링, 인증, 로깅을 Spring Security 기반으로 쉡게 구성하고 싶을 때
  • 트래픽이 많지 않고, MVC에 익숙할 때
  • 익숙한 구조로 Gateway 구성하고 싶은 소규모/중간 규모 프로젝트

예시

📌 Spring MVC (블로킹)

  • 식당에 손님이 오면, 종업원이 한 명씩 전담해서 서빙함. 손님이 메뉴 고를 때, 종업원은 대기하고 아무것도 못 함. (= 블로킹)

📌 Spring WebFlux (논블로킹)

  • 손님이 오면, 종업원은 주문만 받고 다른 손님을 응대함. 음식 나오면 종업원이 전달함. (= 이벤트 기반, 논블로킹)

0개의 댓글