API Gateway - Zuul (중요!!)
API 게이트웨이는 마이크로서비스 아키텍처(MSA)의 핵심 구성 요소 중 하나로, 클라이언트 요청을 받아 처리하는 단일 진입점을 제공하는 서비스입니다.
이는 프록시 서버와 유사한 역할을 하며, 인증, 권한 확인, 모니터링, 로깅 등의 부가 기능도 수행합니다. 전통적인 모노리식 아키텍처에서는 모든 비즈니스 로직이 하나의 서버에 모여있지만, MSA에서는 각 도메인에 대응하는 여러 서비스(서버)가 존재합니다.
또한, 각 서비스는 여러 서버로 구성될 수 있습니다.
이렇게 되면 사용자(클라이언트) 입장에서는 많은 수의 엔드포인트를 관리해야 하는 문제가 발생하며, 엔드포인트가 변경될 때마다 유지 관리가 어려워집니다.
이 문제를 해결하기 위해 모든 요청을 중앙에서 관리하고 분배할 수 있는 API 게이트웨이가 필요하게 됩니다.
위 그림과 같이 Zuul 서버는 단일 end-point 역할을 하며, 이를 위해 Eureka,LoadBalancer 등의 여러 기능을 내장하고 있습니다.
Zuul 서비스 작성
아래와 같이 build.gradle에 Zuul, Spring-retry 라이브러리를 추가로 작성한다.
//build.gradle
implementation 'org.springframework.retry:spring-retry'
implementation 'org.springframework.cloud:spring-cloud-starter-netflix-zuul:2.2.7.RELEASE'
ZuulServerApplication.java 작성
ZuulServerApplication 클래스에 @SpringBootApplication, @EnableZuulProxy와 @EnableDiscoveryClient 어노테이션을 추가한다.
*@EnableDiscoveryClient는 @EnableEurekaClient와 동일하게 작동하지만
@EnableEurekaClient는 Eureka서버일 때만 작동하고,
@EnableDiscoveryClient는 Eureka뿐만 아니라 Consul, Zookeeper도 지원한다.
ZuulServer의 application.properties 파일 작성
Zuul 서버의 관련 내용을 아래와 같이 설정한다.
//application.properties
spring.application.name=zuul
server.port=8080
zuul.routes.catalog.path=/catalogs/**
zuul.routes.catalog.service-id=catalog
zuul.routes.catalog.strip-prefix=false
zuul.routes.customer.path=/customers/**
zuul.routes.customer.service-id=customer
eureka.instance.non-secure-port=${server.port}
eureka.instance.prefer-ip-address=true
eureka.client.service-url.defaultZone=http://localhost:8761/eureka
Zuul 서버의 구동 및 테스트
Zuul 서버의 구동 이전에 Catalogs, Customers, EurekaServer 모두를 실행하고 정상작동을 확인한다. 이 후 Zuul 서버를 기동하고 Eureka 페이지에서 Zuul이 정상적으로 등록되었는지 확인한다.
정상적으로 구동이 확인되었으면 아래의 URL을 통하여 결과를 확인한다. URL 모두 API Gateway인 localhost:8080을 통하여 테스트를 진행한다.
Customers 서비스 URL : http://localhost:8080/customers/1234
Catalogs 서비스 URL : http://localhost:8080/catalogs/customerinfo/1234
하지만 Spring Cloud Zuul은 이제 더는 제공되지 않고, Spring Cloud Gateway(SCG)만 제공한다.
https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/
Spring Cloud Gateway
This project provides an API Gateway built on top of the Spring Ecosystem, including: Spring 6, Spring Boot 3 and Project Reactor. Spring Cloud Gateway aims to provide a simple, yet effective way to route to APIs and provide cross cutting concerns to them
docs.spring.io
기존의 zuul서버라는 이름의 프로젝트명을 Gateway서버로 바꾸자.
프로젝트를 재실행하고 패키지명도 바꾸어 주자.
실행해보고 유레카로 확인해보자.
그럼 이제 Zuul 의존성을 지우고, Gateway 의존성을 추가해준다.
라우팅 설정을 해주자.
로드밸런서를 사용하려면 아래와 같이 설정한다.(유레카를 사용해야만 가능)
그러면 아까와 마찬가지로 localhost:8080으로 catalog와 customer 서비스를 이용 가능하다.
스프링 클라우드 게이트웨이(SCG)의 동작 구조는 아래와 같다.
'DEV > MSA' 카테고리의 다른 글
MSA 개발 가이드(8) - Spring Cloud Bus(RabbitMQ) (0) | 2023.06.27 |
---|---|
MSA 개발 가이드(7) - Spring Cloud Config Server/Client (0) | 2023.06.26 |
MSA 개발 가이드(5) - Spring Cloud Eureka(Service Registry) (0) | 2023.06.19 |
MSA 개발 가이드(4) - Resilience4j(Circuit Breaker) (0) | 2023.06.19 |
MSA 개발 가이드(3) - 마이크로 서비스 아키텍처 구현해보기 (0) | 2023.06.16 |