Spring Cloud by example

2025. 3. 2. 12:55Spring Microservice

🌟 Spring Cloud by Example: 예제 코드 분석 및 정리

이전 챕터에서는 Spring Cloud의 다양한 기술을 소개했습니다.
이번에는 간단한 예제 코드를 통해 서비스 검색(Service Discovery)와 클라이언트 부하 분산(Client-Side Load Balancing) 을 어떻게 쉽게 구현할 수 있는지 살펴보겠습니다.

📌 1. 예제 코드 개요

아래 코드에서는 Eureka 기반 서비스 검색과 RestTemplate을 이용한 원격 호출을 구현하고 있습니다.
이 코드를 직접 실행하려면 먼저 Eureka 서버 및 관련 서비스를 설정해야 합니다.

📌 핵심 개념 요약
• @EnableEurekaClient: 이 애플리케이션이 Eureka에 등록됨을 나타냄.
• RestTemplate: 원격 서비스를 호출할 때 논리적 서비스 ID를 사용.
• Spring Cloud LoadBalancer: 클라이언트 측에서 부하를 분산하여 장애 지점을 줄임.

📌 2. 예제 코드

package com.optima.growth.simpleservice;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.netflix.eureka.EnableEurekaClient;
import org.springframework.http.HttpMethod;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
@RestController
@RequestMapping(value = "hello")
@EnableEurekaClient
public class Application {
    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }

    public String helloRemoteServiceCall(String firstName, String lastName) {
        RestTemplate restTemplate = new RestTemplate();
        ResponseEntity<String> restExchange =
                restTemplate.exchange(
                        "http://logical-service-id/name/{firstName}/{lastName}",
                        HttpMethod.GET, null, String.class, firstName, lastName);
        return restExchange.getBody();
    }

    @RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
    public String hello(@PathVariable("firstName") String firstName,
                        @PathVariable("lastName") String lastName) {
        return helloRemoteServiceCall(firstName, lastName);
    }
}

📌 3. 코드 분석

이 코드에는 Spring Cloud의 주요 기능이 포함되어 있습니다. 아래에서 각 부분을 살펴보겠습니다.

🟢 (1) @EnableEurekaClient - Eureka 서비스 등록

@EnableEurekaClient
  • 이 애플리케이션이 Eureka 서비스 디스커버리 서버에 등록됨을 나타냅니다.
  • 서비스가 실행되면 Eureka 서버에 자동으로 등록되며, 다른 서비스가 이를 검색할 수 있습니다.
  • 📌 참고: spring-cloud-starter-netflix-eureka-client 의존성을 추가하면 @EnableEurekaClient는 생략 가능함.

🟢 (2) RestTemplate을 이용한 원격 호출

RestTemplate restTemplate = new RestTemplate();
ResponseEntity<String> restExchange =
        restTemplate.exchange(
                "http://logical-service-id/name/{firstName}/{lastName}",
                HttpMethod.GET, null, String.class, firstName, lastName);
return restExchange.getBody();
  • RestTemplate은 원격 서비스 호출을 수행하는 Spring의 HTTP 클라이언트입니다.
  • http://logical-service-id/name/{firstName}/{lastName} 에 요청을 보내는데, 물리적 서버 주소가 아닌 논리적 서비스 ID를 사용합니다.
  • Spring Cloud는 내부적으로 Eureka를 통해 해당 서비스의 물리적 위치를 자동으로 찾음.

🟢 (3) 클라이언트 부하 분산 - Spring Cloud LoadBalancer

  • RestTemplate은 내부적으로 Spring Cloud LoadBalancer와 통합되어 있음.
  • Eureka를 통해 검색된 여러 개의 서비스 인스턴스 중 하나를 라운드 로빈(Round-Robin) 방식으로 호출.
  • ➡️ 결과적으로 별도의 중앙 집중식 부하 분산기가 필요 없음.

🟢 (4) API 엔드포인트 정의

@RequestMapping(value = "/{firstName}/{lastName}", method = RequestMethod.GET)
public String hello(@PathVariable("firstName") String firstName,
                    @PathVariable("lastName") String lastName) {
    return helloRemoteServiceCall(firstName, lastName);
}
  • /hello/{firstName}/{lastName} 요청을 처리.
  • 요청을 받아 다른 마이크로서비스의 엔드포인트로 전달.
  • 호출 결과를 그대로 반환.

📌 4. Spring Cloud Eureka + LoadBalancer가 제공하는 이점

서비스 검색 자동화: IP 주소를 하드코딩하지 않아도 서비스 검색이 가능
클라이언트 측 부하 분산: 요청을 여러 인스턴스로 자동 분배하여 부하를 관리
장애 감내성(Fault Tolerance) 증가: 서비스 다운 시 다른 인스턴스로 자동 라우팅
확장성(Scalability) 향상: 마이크로서비스가 동적으로 추가될 수 있음

📌 5. Summary

Spring Cloud를 사용하면 단 몇 개의 어노테이션과 설정만으로 강력한 마이크로서비스 기능을 추가할 수 있습니다.
이 예제는 Spring Cloud의 Eureka, RestTemplate, LoadBalancer 기능을 어떻게 활용하는지 보여주었습니다.

🚀 다음 단계:
다음 챕터에서는 마이크로서비스 개발을 위한 모범 사례(Best Practices)를 살펴보겠습니다.

'Spring Microservice' 카테고리의 다른 글

Config  (0) 2025.03.02
How to build a cloud-native microservice  (0) 2025.03.02
What is Spring Cloud?  (0) 2025.03.02
2.Exploring the microservices world with Spring Cloud  (0) 2025.03.02
SAGA patterns  (0) 2025.02.28