1 분 소요

Netflix Zuul은 Spring Boot 2.4.x 버전부터는 사용할 수 없기 때문에,
대신해서 Spring Cloud Gateway를 사용해 게이트웨이 서비스와 라우팅 서비스를 구현해보도록 하자.

Spring Cloud Gateway는 Zuul과 달리 비동기 처리가 가능하다는 장점이 있다.

프로젝트 생성

first-service

  • Spring Boot: 2.4.2
  • dependencies: Lombok, Spring Web, Eureka Discovery Client

application.yml

server:
  port: 8081

spring:
  application:
    name: my-first-service

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

FirstServiceController.java

@RestController
@RequestMapping("/first-service")
public class FirstServiceController {

    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome First Service";
    }
}

second-service

  • Spring Boot: 2.4.2
  • dependencies: Lombok, Spring Web, Eureka Discovery Client

application.yml

server:
  port: 8082

spring:
  application:
    name: my-second-service

eureka:
  client:
    register-with-eureka: false
    fetch-registry: false

SecondServiceController.java

@RestController
@RequestMapping("/second-service")
public class SecondServiceController {

    @GetMapping("/welcome")
    public String welcome() {
        return "Welcome Second Service";
    }
}

apigateway-service

  • Spring Boot: 2.4.2

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:
      routes:
        - id: first-service
          uri: http://localhost:8081/ # 2. 이동 될 주소
          predicates:
            - Path=/first-service/** # 1. 사용자가 입력한 조건 값
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**

이때, spring.cloud.gateway.routes의 설정이 중요한데,
uri에는 각각의 마이크로 서비스의 ip와 포트번호를 입력한다.

이제 predicates를 해석해보자.
predicates/first-service/** 라면,
http://localhost:8000/first-service/**로 오는 요청을 8081번 포트의 /first-service/** 엔드포이트로 넘긴다는 것이고,

predicates/second-service/** 라면,
http://localhost:8000/second-service/**로 오는 요청을 8082번 포트의 /second-service/** 엔드포이트로 넘긴다는 것이다.

주의 🌟
따라서 FirstServiceController에서 @RequestMapping("/first-service")을 지정하고,
마찬가지로 SecondServiceController에서도 @RequestMapping("/second-service")을 지정해야 한다.

하지만, 나중에 Filter를 다루면서 /first-service, /second-service 등의 필터를 빼고 전달할 수도 있다.



💛 개인 공부 기록용 블로그입니다. 👻

맨 위로 이동하기