Java

[Spring Boot/Spring Cloud] MSA - API Gateway를 사용한 로드밸런싱 방법

cob 2023. 8. 4. 17:39

 

API Gateway란?
MSA는 소규모의 독립적인 서비스로 구성되어 개별적으로 배포, 확장 및 관리할 수 있도록 하는 아키텍처 패턴이다. 이러한 마이크로서비스들은 자체적으로 기능을 제공하며, 각각이 독립적으로 운영될 수 있어야 하는데 이때, API Gateway는 클라이언트와 마이크로서비스 사이의 중간 매개체로 작동하여 통신을 효율적으로 관리한다.

 

API Gateway

 

 


1. Eureka 서버 프로젝트 생성

2023.07.23 - [Java] - [Spring Boot/Spring Cloud] MSA - Netflix Eureka 서버/클라이언트 구축

 

[Spring Boot/Spring Cloud] MSA - Netflix Eureka 서버/클라이언트 구축

Spring Cloud Netflix Eureka란? MSA를 구축하기 위한 Spring Cloud 프로젝트 중 하나로, 서비스 디스커버리(Service Discovery)를 지원하는 도구이다. 마이크로서비스 아키텍처에서는 여러 개의 작은 서비스들로

cocococo.tistory.com

 

 

 


2. Micro Service 프로젝트 생성(Client)

2-1) pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

 

2-2) application.yml

server:
  port: 0

spring:
  application:
    name: my-first-service

eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka
  instance:
    instance-id: ${spring.application.name}:${spring.application.instance_id:${random.value}}
  • defaultZone : Eureka 서버 접속 URL를 세팅한다.
  • instance-id : Eureka는 기본적으로 각각의 인스턴스에 고유한 ID를 할당하여 등록한다. 이 ID는 기본적으로 호스트명(hostname)과 포트(port)를 기반으로 자동으로 생성되지만,  동일한 서비스의 인스턴스를 생성할 경우 하나만 표시된다. 이러한 경우를 방지하기 위해 해당 명령어로 ID를 수동으로 설정해 각각의 인스턴스를 생성해 준다.(port : 0 → 랜덤 포트)

 

2-3) Controller

로드밸런싱을 확인할 간단한 컨트롤러를 구현한다.
package com.example.firstservice;

import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.env.Environment;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;

// @Controller와의 차이는 RequestBody, responseBody를 구현할 수 있다
@RestController
@RequestMapping("/first-service")
@Slf4j
public class FirstServiceController {
    // 환경변수 
    Environment env;

    @Autowired
    public FirstServiceController(Environment env) {
        this.env = env;
    }

    @GetMapping("/check")
    public String check(HttpServletRequest request) {
        return String.format("Server port PORT %s", env.getProperty("local.server.port"));
    }
}

 

 

2-4) 동일 서비스 n개 실행 

Eureka 서버 실행 후 Client 서비스를 실행한다.
  • 일반적인  Run 실행 - 첫 번째 서비스
  • 터미널로 명령어를 사용한 실행
$ mvn spring-boot:run

터미널 프로젝트 실행

  • 아래의 사진과 같이 Eureka 서버에서 등록된 인스턴스를 확인할 수 있다.

Eureka 인스턴스 등록

 

 

 


3. API Gateway 프로젝트 생성

3-1) pom.xml

<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>

 

 

3-2) application.yml

server:
  port: 8000
eureka:
  client:
    register-with-eureka: true
    fetch-registry: true
    service-url:
      defaultZone: http://localhost:8761/eureka

spring:
  application:
    name: apigatway-service
  cloud:
    gateway:
      routes:
        - id: first-service
          uri: lb://MY-FIRST-SERVICE
          predicates:
            - Path=/first-service/**
        - id: second-service
          uri: lb://MY-SECOND-SERVICE
          predicates:
            - Path=/second-service/**
  • uri: lb://MY-FIRST-SERVICE 
    - 기존의 HTTP 프로토콜을 이용해 URI를 찾는 게 아니라, Eureka 서버에서 등록된 클라이언트 요청 정보를 가져온다.

  • predicates : 요청이 라우팅 규칙을 만족하는지를 결정하는 조건을 설정, 요청의 속성(예: URI, 메서드, 헤더 등)을 기반으로 동작한다. 요청의 속성을 검사하고, 조건을 만족하면 해당 요청을 특정 라우트로 보냄
routes:
    - id: first-service
      uri: lb://MY-FIRST-SERVICE
      predicates:
        - Path=/first-service/**
        
// "first-service"를 포함하는 모든 요청을 해당 라우트로 라우팅하라는 의미입니다.
// 이로 인해 Eureka를 통해 등록된 "MY-FIRST-SERVICE" 서비스 인스턴스 중에서 로드 밸런싱을 
// 수행하여 요청을 처리할 수 있게 된다.

 

 

 


4. 로드밸런싱 테스트

위와 같은 작업을 끝냈다면, Client 서비스를 요청을 보내면 운드 로밍(순서대로 돌아가며 수행) 방식으로 서비스를 호출하게 된다

로드밸런싱

  •  API Gateway에서 요청을 받아 특정 라우트에 보내게 되는데 랜덤 포트로인해 4016, 4058로 할당받은 2개의 서비스가 라운드 로밍 방식으로 호출되게 된다.
반응형