Depth: An article to understand the use of Ribbon and the analysis of core principles

1. What is Ribbon

Spring Cloud Ribbon is a set of client-side load balancing tools implemented based on Netflix Ribbon. The Ribbon
client component provides a series of complete configurations, such as timeout, retry, etc.
All machine instances provided by the service are obtained through Load Balancer (LB) , and Ribbon will automatically call these services based on certain rules (polling, random).
Ribbon can also implement our own load balancing algorithm.

1.1 What is client load balancing

The LB in the process is a class library integrated into the consumer, and the provider's address is obtained through the consumer.
In life: Similar to when you go to the train station to queue up (there are three aisles), as long as you are a normal person, you will queue up to the less crowded team
.
In the program: Our consumer can obtain a list of service provider addresses, and then obtain an address to
call according to a certain strategy .

1.2 What is server-side load balancing

In life: Similar to when you go to the train station to queue up, a train station guide tells you that there are
few people in the third channel , and you go to the third channel to line up.

In the program: it is the address of ng that your consumer calls, and ng chooses the forwarding of the request (polling weight, ip_hash, etc.)

2. Quickly integrate Ribbon

Introduce dependencies

<dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring‐cloud‐starter‐netflix‐eureka‐client</artifactId>
 </dependency>
 <!‐‐添加ribbon的依赖, eureka client启动器已经依赖了ribbon,可以不配‐‐>
 <dependency>
  <groupId>org.springframework.cloud</groupId>
  <artifactId>spring‐cloud‐starter‐netflix‐ribbon</artifactId>
 </dependency>

Add @LoadBalanced annotation

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

3. Ribbon core principle

3.1 Ribbon call process

3.2 Ribbon load balancing strategy

  1. RandomRule: Randomly select a Server.

  2. RetryRule: For the retry mechanism on the selected load balancing strategy machine, when the
    server selection is unsuccessful within a configuration period of time , it will always try to use the subRule method to select an available server.

  3. RoundRobinRule: Polling selection, polling index, select the Server corresponding to the index.

  4. AvailabilityFilteringRule: Filter out the
    back-end servers marked as circuit tripped that have failed to connect all the time , and filter out those high-concurrency back-end servers or use an AvailabilityPredicate
    to include the logic of filtering the server. In fact, it is to check the operation of each server recorded in the status. status.

  5. BestAvailableRule: Select a server with the smallest concurrent request and examine the servers one by one.
    If the server is tripped, skip it.

  6. WeightedResponseTimeRule: Weighted according to the response time. The longer the response time and the
    smaller the weight , the lower the probability of being selected.

  7. ZoneAvoidanceRule: The server is selected to compound the performance of the area where the server is located and the availability of the
    server.

3.2.1 Modify the default load balancing policy

 @Configuration
 public class AppConfig {
    
    

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

3.2.2 Custom load balancing strategy

1) Custom load algorithm

public class MyRandomRule extends AbstractLoadBalancerRule {
    
    

  /** 总共被调用的次数,目前要求每台被调用5次 */
  private int total = 0;
  /** 当前提供服务的机器号 */
  private int currentIndex = 0;

  public Server choose(ILoadBalancer lb, Object key) {
    
    
  if (lb == null) {
    
    
  return null;
  }
  Server server = null;

  while (server == null) {
    
    
  if (Thread.interrupted()) {
    
    
  return null;
  }
  //激活可用的服务
  List<Server> upList = lb.getReachableServers();
  //所有的服务
  List<Server> allList = lb.getAllServers();

  int serverCount = allList.size();
  if (serverCount == 0) {
    
    
  return null;
  }

  if (total < 5) {
    
    
  server = upList.get(currentIndex);
  total++;
  } else {
    
    
  total = 0;
  currentIndex++;
  if (currentIndex >= upList.size()) {
    
    
  currentIndex = 0;
    }
  }
  if (server == null) {
    
    
  Thread.yield();
  continue;
  }

  if (server.isAlive()) {
    
    
  return (server);
  }

  // Shouldn't actually happen.. but must be transient or a bug.
  server = null;
  Thread.yield();
  }
  return server;
  }

  @Override
  public Server choose(Object key) {
    
    
  return choose(getLoadBalancer(), key);
  }

  @Override
  public void initWithNiwsConfig(IClientConfig clientConfig) {
    
    
    }
 }

2) Define the configuration class outside the package scanned by the SpringBoot main program

 @Configuration
 public class MySelfRule {
    
    
 @Bean
  public IRule myRule(){
    
    
  return new MyRandomRule();
  }
 }

Note: The custom load balancing strategy cannot be written in
the place scanned by @CompentScan annotation of @SpringbootApplication , otherwise the custom configuration class will be shared by all RibbonClients.

3) Use @RibbonClient to specify the load balancing strategy, add @RibbonClient to the SpringBoot main program to import
the configuration class

 @SpringBootApplication
 @RibbonClient(name = "service‐order",configuration = MySelfRule.class)
 public class ServiceMemberApplication {
    
    }

3.3 Ribbon related interfaces
Reference: org.springframework.cloud.netflix.ribbon.RibbonClientConfiguration
IClientConfig: Ribbon's client configuration, which is implemented by DefaultClientConfigImpl by default.

IRule: Ribbon's load balancing strategy is implemented by default using ZoneAvoidanceRule. This strategy can
select the best zone instance for access in a multi-zone environment.

IPing: Ribbon's instance checking strategy, which is implemented by DummyPing by default. This checking strategy is a special
implementation. In fact, it does not check whether the instance is available, but always returns true. By default, all service instances are considered
available.

ServerList: The maintenance mechanism of the service instance list, which is implemented by ConfigurationBasedServerList by default.

ServerListFilter: Service instance list filtering mechanism, ZonePreferenceServerListFilter is adopted by default. This
strategy can preferentially filter out service instances in the same region as the requester.

ILoadBalancer: Load balancer, implemented by ZoneAwareLoadBalancer by default, it has the ability of region
awareness.
Modify the configuration:

 # 使用<clientName>.ribbon.<key>=<value>的形式进行配置
 # 参考org.springframework.cloud.netflix.ribbon.PropertiesFactory
 # PingUrl: Get http://192.168.3.1:8010/
 # 指定IPing
 service‐order.ribbon.NFLoadBalancerPingClassName=\
  com.netflix.loadbalancer.PingUrl
 # 指定IRule
 service‐order.ribbon.NFLoadBalancerRuleClassName=\
  com.netflix.loadbalancer.RandomRule

4 Ribbon source code analysis


(Friends who need the original picture can follow my WeChat public account: input: Ribbon)

This article is shared with friends who need to interview and brush up questions, and I wish you all the best to get the offer you want. This information mainly includes Java basics, data structures, jvm, multithreading, etc. Due to limited space, only a small part is shown below. Interview questions, friends who need the full version can click a link to jump to receive, link: click here to download for free, get code: CSDN

Insert picture description here

Guess you like

Origin blog.csdn.net/qq_41770757/article/details/110552363