“This is the 16th day of my participation in the November Gwen Challenge. See details of the event: The Last Gwen Challenge 2021”.

Hello, I am Wukong.

So if you were to design a load balancing component, what would you do?

Here are a few factors to consider:

  • How do I get and synchronize the server list? It involves interaction with the registry.
  • How to split the load? The allocation strategy is involved.
  • How do I intercept a client request and select a server to forward it? Request interception is involved.

With these questions in mind, let’s learn how to design a load balancer based on the principles of load balancing and the Ribbon architecture.

In this article we explain how the Ribbon initializes:

How the Ribbon initializes

When we look at the Ribbon source code, we need to find a breakthrough, and the @loadBalanced annotation is a good entry point.

Here is a flowchart for initializing the Ribbon:

The code to add the annotation looks like this:

@LoadBalanced
@Bean
public RestTemplate getRestTemplate(a) {
	return new RestTemplate();
}
Copy the code

Step 1: Ribbon have a automatic configuration class LoadBalancerAutoConfiguration, SpringBoot load automatic configuration class, will go to initialize the Ribbon.

The second step: When we annotate RestTemplate or AsyncRestTemplate, the Ribbon initializes to collect RestTemplate and AsyncRestTemplate with @loadBalanced. Put them in a List.

Step 3: The RestTemplateCustomizer in the Ribbon customizes each RestTemplate by adding a LoadBalancerInterceptor.

Step 4: Get the list of services from the Eureka registry and save it in the Ribbon.

Step 5: Load the YMAL configuration file, configure the load balancing configuration, and create an ILoadbalancer instance.

About the author: Wu Kong, 8 years of experience in Internet development and architecture, explains distributed, architecture design, Java core technology with stories. Author of “JVM Performance Optimization Practice” column, open source “Spring Cloud Practice PassJava” project, public account: Wukong chat architecture. This article is available at www.passjava.cn