공부/Spring

Spring Cloud로 개발하는 마이크로서비스 애플리케이션_API Gateway Service_3

데부한 2023. 2. 15. 00:00
반응형

 

 

Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA)

나는 Netflix Zuul.... 강의 때 임의로 Spring Cloud Gateway를 사용했었는데....이렇게 따로 강의가 있었다니...! 복습하는 셈치고 간략하게 쑥쑥 적어야겠다.

 

Spring Cloud Gateway - 프로젝트 생성

Spring Boot 버전은 2.7.8로 설정했다.

 

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

application.yml 파일에 route에 대한 정보를 여러 개 설정할 수 있다. 

uri는 포워딩 될 주소를 기재하고 predicates는 포워딩 될 조건절이다. 사용자가 입력한 Path가 predicates의 path와 같으면 uri에 기재된 주소로 포워딩 시킨다.

 

서버 실행

서버를 실행하면 콘솔에 Netty started on port 8000 문자를 확인할 수 있다. 여태 우리는 Tomcat을 이용하여 서버를 띄웠는데 이번에는 Netty라는 내장 서버를 이용하여 띄웠다. Tomcat으로 서버를 띄우는 건 동기 방식이고, Spring Cloud Gateway를 이용해 서버를 띄우면 비동기 방식으로 서비스가 실행된다.

크롬에서 first-service와 second-service 주소를 띄워보자.

두 페이지 다 404 에러가 발생한다.

이유는 predicates에 기재된 Path가 uri에 붙어서 포워딩 되는데 위에서 설정했던 대로 URL을 만들면

http://localhost:8081/first-service/**
http://localhost:8082/second-service/**

이렇게 만들어진다. 그럼 문제가 뭐냐면 first-service의 컨트롤러를 봐보자.

@RestController
@RequestMapping("/")
public class FirstServiceController { ... }

클래스 영역의 @RequestMapping이 "/"로만 설정되어있기 때문에 "http://localhost:8081/welcome"으로 클라이언트에서 요청해야지만 정상적인 페이지가 뜬다. 고로 @RequestMapping의 값을 변경하자.

 

Controller 수정

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

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

컨트롤러 수정 후 각 프로젝트를 재실행한다.

크롬에서 확인한다.

404 에러 없이 페이지를 잘 불러온다.

 


- 출처 : 인프런 Spring Cloud로 개발하는 마이크로서비스 애플리케이션(MSA) 강의

반응형