카테고리 없음

Spring Cloud Gateway - 프로젝트 생성

백엔드 개발자 2023. 7. 31. 21:49

 

<dependencies>
   <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-gateway</artifactId>
   </dependency>

   <dependency>
      <groupId>org.projectlombok</groupId>
      <artifactId>lombok</artifactId>
      <optional>true</optional>
   </dependency>
   <dependency>
      <groupId>org.springframework.boot</groupId>
      <artifactId>spring-boot-starter-test</artifactId>
      <scope>test</scope>
   </dependency>
   <dependency>
      <groupId>org.springframework.cloud</groupId>
      <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
   </dependency>
</dependencies>

Spring gateway,

Lombok

Eureka

3가지 dependency를 추가하여 진행한다.

 

 

 

application.yml

server:
  port: 8000


#유레카는 기본적으로 클라이언트역할로서 어딘가에 등록하는 작업 진행.
#그러나 현재는 server의 역할을 할 것이기 때문에, 자신의 정보를 자신에게 등록할 필요가 없다. 그래서 false 처리.
eureka:
  client:
    register-with-eureka: false #eureka의 registry에 등록할지 여부이다.
    fetch-registry: false #registry의 정보를 가져올 지 여부.
    service-url:
      defaultZone: http://localhost:8761/eureka #



spring:
  application:
    name: apigateway-service
  cloud:
    gateway:
      routes: #Zuul 서비스의 라우팅과 유사한 역할.
        - id: first-service
          uri: http://localhost:8081/
          predicates:
            - Path=/first-service/** # 조건. Path 경로가 일치하면 해당 uri로 이동시킨다.
        - id: second-service
          uri: http://localhost:8082/
          predicates:
            - Path=/second-service/**

 

클라이언트 요청 -> API Gateway -> Service Discovery(Eureka Server)에서 마이크로서비스 위치 정보 확인 -> API Gateway -> 해당 마이크로서비스로 요청 -> API Gateway로 응답 반환 -> 클라이언트에게 반환

 

 

Spring cloud ApiGateway는 비동기 방식을 지원하기 때문에, 내부적으로 netty서버가 동작한다.

 

 

 

 

주의해야 할 부분: apigateway에서 호출시 Path경로가 그대로 호출되서 404에러가 발생할 수 있는 문제

 

실제로 호출되는 주소는 아래와 같게 된다.

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

 

그러나 first-service의 controller를 보면

localhost:8081/welcome일 경우 아래 메서드를 실행한다.

즉, 호출되는 주소가 

 http://localhost:8081/first-service/welcome이면

first-service에서 실제 호출가능한 주소는

http://localhost:8081/welcome 이므로, 주소가 달라서 404에러가 뜨게 된다.

 

 

 

해결

호출되는 주소 변경되도록 RequestMapping을 추가한다.

 

 

 

재호출 결과

 

 

 

Ref :

https://velog.io/@backtony/Spring-Cloud-Eureka-API-Gateway

 

Spring Cloud - Eureka, API Gateway

그림1Service Discovery는 단어 직역 그대로, 외부의 서비스들이 마이크로서비스를 검색하기 위해 사용하는 일종의 전화번호부와 같은 역할로 각각의 마이크로서비스가 어느 위치에 있는지를 등록

velog.io

 

https://sabarada.tistory.com/62

 

 

 

 

https://www.inflearn.com/course/lecture?courseSlug=%EC%8A%A4%ED%94%84%EB%A7%81-%ED%81%B4%EB%9D%BC%EC%9A%B0%EB%93%9C-%EB%A7%88%EC%9D%B4%ED%81%AC%EB%A1%9C%EC%84%9C%EB%B9%84%EC%8A%A4&unitId=68414 

 

 

 

학습 페이지

 

www.inflearn.com