0Pricing
API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) · 강의

Spring Cloud LoadBalancer를 사용한 부하 분산

여러 서비스 인스턴스로 요청을 라우팅할 때 클라이언트 측 부하 분산에 Spring Cloud LoadBalancer를 활용해 보세요.

Spring Cloud LoadBalancer를 사용한 부하 분산은(는) CoddyKit의 무료 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의입니다. 이것은 4개 중 3번째 강의입니다. 아래에서 전체 강의를 무료로 읽을 수 있으며, 내장 코드 에디터와 24/7 AI 튜터와 함께 브라우저에서 직접 실습할 수 있습니다. 이 강의는 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 학습 경로의 일부이며, 진행 상황이 웹과 CoddyKit 앱에 동기화됩니다. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 총 4개의 강의가 포함되어 있습니다.

이 강의의 일부는 아직 번역되지 않았으며 영어로 표시됩니다.

What is Client-Side Load Balancing?

In a microservices architecture, you often have multiple instances of the same service running. Client-side load balancing means the client (the service consumer) is responsible for choosing which instance to send a request to.

Unlike server-side load balancing (like Nginx), where a central proxy distributes requests, here the client actively participates in the decision. This can reduce network hops and improve responsiveness.

Introducing Spring Cloud LoadBalancer

Spring Cloud LoadBalancer is a client-side load balancer that works seamlessly with Spring Cloud applications. It's the modern successor to Netflix Ribbon in the Spring ecosystem.

It integrates with service discovery mechanisms (like Eureka or Consul) to get a list of available service instances and then applies a load balancing algorithm to select one for each request.

Adding LoadBalancer to Your Project

To use Spring Cloud LoadBalancer, you typically add the spring-cloud-starter-loadbalancer dependency to your Spring Boot project. This starter brings in all necessary components.

It's often used alongside a service discovery client (e.g., Eureka Client) so LoadBalancer knows which service instances are available.

Load Balancing with RestTemplate

You can easily enable client-side load balancing for RestTemplate by adding the @LoadBalanced annotation to its bean definition. This tells Spring Cloud to intercept calls and use LoadBalancer.

Notice how we call the service using its logical name (MY-SERVICE) instead of a specific IP:port.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.client.RestTemplate;

@SpringBootApplication
public class RestTemplateClient {

  @LoadBalanced
  @Bean
  public RestTemplate restTemplate() {
    return new RestTemplate();
  }

  public static void main(String[] args) {
    SpringApplication.run(RestTemplateClient.class, args);
    
    // Example usage (in a real app, this would be in a service)
    // RestTemplate restTemplate = applicationContext.getBean(RestTemplate.class);
    // String response = restTemplate.getForObject("http://MY-SERVICE/hello", String.class);
    // System.out.println("Response from MY-SERVICE: " + response);
  }
}

Load Balancing with WebClient

For reactive applications, WebClient is the preferred choice. You can enable load balancing for it by applying @LoadBalanced to a WebClient.Builder bean.

Similar to RestTemplate, you use the service's logical name in the URL, and LoadBalancer handles the instance resolution.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.loadbalancer.LoadBalanced;
import org.springframework.context.annotation.Bean;
import org.springframework.web.reactive.function.client.WebClient;

@SpringBootApplication
public class WebClientClient {

  @LoadBalanced
  @Bean
  public WebClient.Builder webClientBuilder() {
    return WebClient.builder();
  }

  public static void main(String[] args) {
    SpringApplication.run(WebClientClient.class, args);

    // Example usage (in a real app, this would be in a service)
    // WebClient webClient = applicationContext.getBean(WebClient.Builder.class).build();
    // webClient.get().uri("http://MY-SERVICE/greet")
    //     .retrieve().bodyToMono(String.class)
    //     .subscribe(response -> System.out.println("Response: " + response));
  }
}

How Service Discovery Powers It

Spring Cloud LoadBalancer doesn't magically know about service instances. It relies on service discovery, like Eureka or Consul, to provide a list of healthy, available instances for a given service ID.

When a client makes a request using a logical service name (e.g., MY-SERVICE), LoadBalancer queries the service registry, gets the list of instances, and then picks one.

Default Strategy: Round Robin

By default, Spring Cloud LoadBalancer uses the Round Robin algorithm. This means it cycles through the available service instances in order, distributing requests evenly.

For example, if you have three instances (A, B, C), the first request goes to A, the second to B, the third to C, the fourth back to A, and so on.

Gateway Routing with LoadBalancer

Spring Cloud Gateway automatically integrates with Spring Cloud LoadBalancer. When you define a route using a service ID (e.g., lb://MY-SERVICE), the Gateway uses LoadBalancer to resolve the actual instance address.

This means your gateway can route requests to multiple instances of a backend service without you needing to manually manage their IPs and ports.

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;
import org.springframework.cloud.gateway.route.RouteLocator;
import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;
import org.springframework.context.annotation.Bean;

@SpringBootApplication
@EnableDiscoveryClient // Enables service discovery client (e.g., Eureka)
public class GatewayApplication {

  public static void main(String[] args) {
    SpringApplication.run(GatewayApplication.class, args);
  }

  @Bean
  public RouteLocator customRouteLocator(RouteLocatorBuilder builder) {
    return builder.routes()
      .route("my_service_route", r -> r.path("/api/**")
        .uri("lb://MY-SERVICE")) // 'lb://' indicates load-balanced service
      .build();
  }
}

Customizing Load Balancing Strategies

While Round Robin is the default, Spring Cloud LoadBalancer is extensible. You can configure custom load balancing algorithms if your needs are more complex.

For example, you might want a 'Least Connections' strategy, which sends requests to the instance with the fewest active connections, or a 'Sticky Session' approach to route a user's requests consistently to the same server.

Quick Check: LoadBalancer Purpose

Which of the following are primary benefits or characteristics of using Spring Cloud LoadBalancer?

Recap: Client-Side Load Balancing

We've explored Spring Cloud LoadBalancer, a key component for building resilient microservices. It enables clients to intelligently distribute requests across multiple instances of a service.

  • It's a client-side solution, distinct from server-side proxies.
  • It works with service discovery (e.g., Eureka) to find service instances.
  • You can use it with @LoadBalanced RestTemplate or WebClient.Builder.
  • It's automatically integrated into Spring Cloud Gateway for routing.
  • The default load balancing strategy is Round Robin.

This ensures your applications can scale horizontally and remain available even if some service instances fail.

자주 묻는 질문

“Spring Cloud LoadBalancer를 사용한 부하 분산” 강의는 무료인가요?

네 — “Spring Cloud LoadBalancer를 사용한 부하 분산” 전체 내용을 이 웹사이트에서 무료로 읽을 수 있습니다. 인터랙티브하게 실습하려면(내장 코드 에디터와 24/7 AI 튜터), CoddyKit PRO로 업그레이드하면 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의 전체를 잠금 해제할 수 있습니다. API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 총 4개의 강의가 포함되어 있습니다.

“Spring Cloud LoadBalancer를 사용한 부하 분산”에서 뭘 배우나요?

여러 서비스 인스턴스로 요청을 라우팅할 때 클라이언트 측 부하 분산에 Spring Cloud LoadBalancer를 활용해 보세요. 브라우저에서 직접 실행하는 실습 코드로 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 배우며, 24/7 AI 튜터가 강의를 진행하면서 질문에 답변해줍니다.

API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)을(를) 시작하는 데 경험이 필요한가요?

사전 경험은 필요하지 않습니다. CoddyKit의 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)은(는) 초급자부터 고급 학습자까지를 위해 구성되어 있으므로, 여기서 시작하거나 처음부터 시작할 수 있으며 자신의 속도대로 진행할 수 있습니다. 이것은 4개 중 3번째 강의입니다.

“Spring Cloud LoadBalancer를 사용한 부하 분산” 강의는 얼마나 걸리나요?

대부분의 CoddyKit 강의는 약 5~10분이 소요됩니다. 각 강의는 간결하고 인터랙티브하여 꾸준한 진행이 가능하며, 웹과 앱에서 중단한 부분부터 바로 시작할 수 있습니다.

이 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에서 코드를 작성하고 실행할 수 있나요?

네. 모든 API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) 강의에는 내장 코드 에디터가 포함되어 있으므로, 브라우저에서 바로 실제 코드를 작성하고 실행한 후 즉시 AI 피드백을 받을 수 있습니다 — 로컬 설정이 필요 없습니다.

이 강의의 모든 강의

  1. Eureka 및 Consul 연동
  2. 서비스 검색을 사용한 동적 라우팅
  3. Spring Cloud LoadBalancer를 사용한 부하 분산
  4. lb:// URI 및 검색 로케이터
← API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway)(으)로 돌아가기