การกระจายโหลดด้วย Spring Cloud LoadBalancer
ใช้ Spring Cloud LoadBalancer เพื่อกระจายโหลดที่ฝั่งไคลเอ็นต์เมื่อส่งคำขอไปยังอินสแตนซ์หลายรายการของบริการ
การกระจายโหลดด้วย Spring Cloud LoadBalancer เป็นบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ฟรีบน CoddyKit นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน คุณสามารถอ่านบทเรียนทั้งหมดด้านล่างฟรี — จากนั้นลองปฏิบัติด้วยตัวคุณเองในเบราว์เซอร์พร้อมตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7 บทเรียนนี้เป็นส่วนหนึ่งของเส้นทางการเรียน 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 RestTemplateorWebClient.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” ฟรีให้อ่านที่นี่บนเว็บ เพื่อปฏิบัติแบบโต้ตอบ (ตัวแก้ไขโค้ดในตัวและติวเตอร์ AI ตลอด 24/7) และปลดล็อคส่วนที่เหลือของคอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ให้อัปเกรดเป็น CoddyKit PRO คอร์ส API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) มีบทเรียนทั้งหมด 4 บทเรียน
คุณจะเรียนรู้อะไรในบทเรียน “การกระจายโหลดด้วย Spring Cloud LoadBalancer”
ใช้ Spring Cloud LoadBalancer เพื่อกระจายโหลดที่ฝั่งไคลเอ็นต์เมื่อส่งคำขอไปยังอินสแตนซ์หลายรายการของบริการ คุณปฏิบัติ API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ด้วยโค้ดที่ใช้งานได้จริงที่คุณเรียกใช้โดยตรงในเบราว์เซอร์ และติวเตอร์ AI ตลอด 24/7 ตอบคำถามของคุณขณะที่คุณไปผ่านบทเรียน
คุณต้องมีประสบการณ์ก่อนที่จะเริ่มเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) หรือไม่
ไม่จำเป็นต้องมีประสบการณ์มาก่อน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) บน CoddyKit ออกแบบมาสำหรับผู้เริ่มต้นไปจนถึงผู้เรียนขั้นสูง คุณสามารถเริ่มต้นที่นี่หรือเริ่มจากตัวแรกและเรียนด้วยความเร็วของคุณเอง นี่คือบทเรียนที่ 3 จากทั้งหมด 4 บทเรียน
บทเรียน “การกระจายโหลดด้วย Spring Cloud LoadBalancer” ใช้เวลานานแค่ไหน
บทเรียน CoddyKit ส่วนใหญ่ใช้เวลาประมาณ 5–10 นาที แต่ละบทเรียนจึงสั้นและเป็นแบบโต้ตอบ คุณสามารถก้าวหน้าอย่างต่อเนื่องและกลับมาเรียนต่อจากตรงที่เพิ่งหยุดบนเว็บและแอปได้เลย
ฉันเขียนและรันโค้ดในบทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) นี้ได้ไหม
ได้ บทเรียน API Gateway & Reverse Proxy (Nginx + Spring Cloud Gateway) ทุกบทมีตัวแก้ไขโค้ดในตัว คุณจึงเขียนและรันโค้ดจริงได้เลยในเบราว์เซอร์ และได้รับข้อเสนอแนะจาก AI ในทันที — ไม่ต้องติดตั้งในเครื่องของคุณ
บทเรียนทั้งหมดในหลักสูตรนี้
- การผสานรวมกับ Eureka และ Consul
- การกำหนดเส้นทางแบบไดนามิกด้วยการค้นหาบริการ
- การกระจายโหลดด้วย Spring Cloud LoadBalancer
- URI lb:// และตัวระบุตำแหน่งบริการ